Vue.js Basic Learning 07 — Rendering and Working With Lists

<div id="app">
<ul>
<div v-for="task in tasks">
<li>{{ task }}</li>
</div>
</ul>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
tasks: [
'Go to the store',
'Go to the bank',
'Go to the doctor'
]
}
});
</script>

當 tasks 為字串的陣列時,情況較單純直接拋給樣板即可。但是當 tasks 還有其他資訊,格式若為物件:

tasks: [
{name: "Go to the store", completed: false},
{name: "Go to the bank", completed: false},
{name: "Go to the doctor", completed: true}
]

呈現時樣板理當改為:

<li>{{ task.name }}</li>

若是要在 <li> 上加入 css 樣式,這樣為一律有 delete-me 樣式:

<li class="delete-me">{{ task.name }}</li>

這樣寫則為動態綁定,雙引號內可以讀取的到 task.completed 並根據判斷式決定是否要載入樣式:(v-bind:class 可以簡寫為 :class)

<li :class="task.completed ? 'delete-me' : ''">{{ task.name }}</li>

但是若沒有寫 v-bind,則會直接得到明顯錯誤的樣式:

<li class="task.completed ? 'delete-me' : ''">{{ task.name }}</li>

而若是要自訂其他變數,這樣寫會失敗,一樣沒有設定樣式:

<li :class="thing">{{ task.name }}</li>

而若在 Vue data 裡面有設定好資料的話就可以讀到樣式 gogo

data: {
thing: 'gogo',
className: ['class_a', 'class_b'],
tasks: [
{name: "Go to the store", completed: false},
{name: "Go to the bank", completed: false},
{name: "Go to the doctor", completed: true}
]
}

如上設定 className,也可以用陣列載入樣式:

<li :class="className">{{ task.name }}</li>

會得到:

由此可約略得知,若寫 v-bind:class 是在告知 html class 這個屬性的,也就是雙引號裡面的內容,不是一般的字串,而是 Vue data 的變數。如果找不到這個變數的話就不會 render 上去。

那如果很直覺的想要這樣寫:

<li class="{{ task.completed ? 'delete-me' : '' }}">{{ task.name }}</li>

則會在 console 就得到錯誤訊息:

[Vue warn]: class="{{ task.completed ? 'delete-me' : '' }}": Interpolation inside attributes has been deprecated. Use v-bind or the colon shorthand instead.

那若是自創的屬性?:abc=”abc”abc=”abc” 的差別一樣在於有沒有設定 v-bind,會讓後面屬性的值被識別成字串或是 Vue data 的變數:

<li :abc="abc">{{ task.name }}</li>
// here is javascript:
abc: ['class_a', 'class_b'],

html 會 render 成:

<li abc=”class_a,class_b”>Go to the doctor</li>

或是:

<li abc=”abc”>Go to the doctor</li>

最後將 list 加上個 toggle 功能,對每個 list click 時就可以切換刪除線。可以宣告個 Vue method 或是直接用 inline 寫法達成:

@click="task.complete = !task.complete"

@click 是 v-on:click 的簡寫,如同 v-bind: 一樣,會對後面 “” 內視為 javascript 區塊。