v-for
列表渲染透过v-for
指令,将资料里的阵列或是物件重复渲染在画面上。
遍历物件资料
:<div id="app">
<ul>
<li v-for="(items, key, index) in item">
{{ items }}:{{ key }}:{{ index }}
</li>
</ul>
</div>
const vm = Vue.createApp({
data() {
return {
item: {
one: 1,
two: 2,
three: 3,
}
}
}
}).mount('#app');
迭代物件
中的元素,第二个参数key
是键值,第三个参数index
是索引值。
遍历阵列资料
:<div id="app">
<ul>
<li v-for="(item, index) in arr">
{{ item.name }} - {{ index }} - {{ item.id }}
</li>
</ul>
</div>
const vm = Vue.createApp({
data() {
return {
arr: [
{ name: "one" ,id: "1"},
{ name: "two" ,id: "2"},
{ name: "three" ,id: "3"}
]
};
}
}).mount("#app");
迭代阵列
中的元素,第二个参数index
是键值。可以使用item.name
点的运算子,带出属性name
。
v-for
筛选<div id="app">
<ul>
<li v-for="item in filterNum">{{ item }}</li>
</ul>
</div>
const vm = Vue.createApp({
data() {
return {
num: [1,2,3,4,5,6,7,8]
}
},
computed: {
filterNum() {
return this.num.filter(function(itemNum){
return itemNum % 2 === 0
});
}
}
}).mount('#app');
arrow function:
const vm = Vue.createApp({
data() {
return {
num: [1,2,3,4,5,6,7,8]
}
},
computed: {
filterNum() {
return this.num.filter(itemNum =>
itemNum % 2 === 0
);
}
}
}).mount('#app');
大括弧拿掉,箭头函式能自带return。
v-for
一定要加:key
?相同父元素的子元素都必须有独特的key
值,重复的key
会造成画面渲染错误。
未绑定:key
版本:
<div id="app">
<ul>
<li v-for="(item, index) in products">{{ index }} - {{ item.name }} - {{ item.price}}
<input type="text">
</li>
</ul>
<button type="button" @click="reverseArray">反转</button>
</div>
const vm = Vue.createApp({
data() {
return {
products: [
{
name: '上衣',
price: 500
},
{
name: '裤子',
price: 1000
},
{
name: '鞋子',
price: 2000
},
{
name: '帽子',
price: 2000
},
]
}
},
methods: {
reverseArray() {
this.products.reverse();
}
}
}).mount('#app');
在第一个input
输入数字1234:
按下反转:
帽子-2000跑到最下面,input:1234
还停留在一行,这是Vue.js
的机制,当他认为该区块没有变化,就不会重新进行渲染,之後补上 v-bind:key="itme.name"
就可以正常运作了,之後使用v-for
指令一定要搭配:key
来使用,可以避免一些错误。
如有错误欢迎指教!
<<: DAY13 - 档案类的物件关系厘清(2) - Object URL, Data URI
>>: Day14 Vue directives(v-for)上
宣告变数的资料型别--阵列 1.数值( Number ) 2.字串( String ) 3.布林值(...
Microsoft AZ-900 exam preparation is tough but you...
你是说...树吗? 嘿~丢!铁人赛至今已经过半,实在是油尽灯枯,想不到主题了,刚好看到这两个很赞的树...
回圈指的是「重复做某件事,次数随着数值『递增」或『递减』,当数值满足所设的条件,则退出回圈」。 所...
初探物联网 1.物联网的源起 物联网这个概念其实出自於1999年麻省理工学院建立了一个自动识别中心,...