Vue 101-Day 5

|

Vue 使用 HTML 為基底的 template syntax,讓使用者使用宣告式的方法將 DOM 綁定至 Vue instance 的資料。

 底層中,Vue 將這些 template 編譯為 Virtual DOM render functions。

Interpolations

Text

最普遍的插值方法就是使用雙花括號 {{ }} 的方式,寫過 Angular 的人應該會覺得熟悉

<div id="app">
     {{ message }} 
</div>

若加上v-once這個 directive,就代表這個值只要綁定一次,之後值若有改變也不會更新到 DOM

Raw HTML

使用 interpolation 會將資料當成文字處理,所以直接綁定 HTML 語法也是輸出文字。 若要輸出 HTML 語法的話,則要使用 v-html 這個 directive。

<div id="app-5">
  <p>using double curly braces: </p>
  <p v-html="rowHTML"></p>
</div>

Attribute

再 HTML attribute 裡並不能使用 double curly braces,所以要改使用v-bind這個 directive

範例為綁定 title 屬性,所以當滑鼠停留在這個 tag 時,則會顯示 title 這個 data

<div id="app-5" v-bind:title="title">
  Hi~~~~
</div>

JavaScript Expressions

除了綁定資料之外,也支援使用 JavaScript Expressions

 {{ ok ? 'I am fine' : 'not good.' }} 
 {{ title.split('').reverse().join('') }} 

Directive

最好適別的方法就是開頭是以v-為開頭,就是 Vue 所提供的 Directive

<p v-if="seen">
  Now you see me.
</p>

Arguments

某些 directive 可以接受參數,在directive之後使用冒號表示

如下範例:使用 v-bind directive 綁定 title 這個 HTML attribute。

這裡的:title 就是 arguments

<div id="app-5" v-bind:title="title">
  Hi~~~~
</div>

v-on 這個 directive 可以綁定 DOM 事件,將上述範例再拿來改一下

如下所示:這裡綁定 click 的 DOM 事件

<p v-if="seen" v-on:click="clickMe">
  Now you see me.
</p>

Dynamic Arguments

此用法再版本2.6以上才能使用,語法為一個中括號[]

範例如下:

<p v-on:[eventName]="clickMe" v-on:[attributeName]="title">
  Now you see me.
</p>

注意

上述使用[eventName]、[attributeName],照理來說對應的 data 應該也要是 eventName、attributeName 才對,但是 卻發生了錯誤訊息

[Vue warn]: Property or method “attributename” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. (found in )

這是由於 HTML 的規定造成的,命名需要更改為小寫

限制

值不能為 null,否則會出現錯誤

[Vue warn]: Invalid value for dynamic directive argument (expected string or null): undefined (found in <Anonymous>)

Shorthands

Vue 提供針對 directive 的縮寫語法,讓使用者可以用更快完成語句。

v-on 縮寫

語法為:@ + eventName

<!-- 完整語法 -->
<p v-on:click="clickMe"> Now you see me.</p>

<!-- 縮寫語法 -->
<p @click="clickMe">Now you see me.</p>

<!-- dynamic attribute 縮寫語法 -->
<p @[eventname]="clickMe"> Now you see me.</p>

v-bind 縮寫

語法為:: + attributeName

<!-- 完整語法 -->
 <p v-bind:title="title"> Now you see me.</p>

<!-- 縮寫語法 -->
 <p :title="title">Now you see me.</p>

 <!-- dynamic attribute 縮寫語法 -->
  <p :[attributename]="title">Now you see me.</p>

參考資料:

Comments