Vue Academy #4:v-for 指令
欢迎来到全新的 Vue 学院!这里将汇集大量关于 Vue 的文章!我拥有 2.5 年的 Vue 开发经验,可以分享一些相关知识!
使用 Vue 时,你可以使用一些指令,今天我们将v-for详细了解一下!
这是什么?
v-for是一个用于根据数组或对象渲染项目列表的指令。
<template>
<div>
<div
v-for="item in toto"
:key="item"
>
{{ item }}
</div>
</div>
</template>
<script>
import Vue from "vue"
export default Vue.extend({
data() {
return {
toto: [ 'first', 'second', 'third' ],
}
},
})
</script>
在这个组件中,我们将包含如下所示的三个div元素👇
first
second
third
您还可以获取迭代项的当前索引。
<div
v-for="(item, index) in toto"
:key="item"
>
{{ item }} {{ index }}
</div>
它也适用于对象!如果我们toto: [ 'first', 'second', 'third' ]用一个对象替换它,例如toto: { a: 1, b: 2, c: 3 }
我们有👇
1
2
3
我们还可以获取当前密钥!
<div
v-for="(item, attribute) in toto"
:key="item"
>
{{ item }} {{ attribute }}
</div>
该key属性
以上述例子为例,你可以问:这个:key值是多少?
在 Vue 中,:key所有组件都会使用 `key` 属性。如果 `key` 发生变化,组件就会重新加载(触发 `destroy` 和 `created` 钩子)。这是一种简单有效的组件重新加载方式!
通常情况下,你不需要处理这个属性,但在……中v-for,key是MANDATORY!
为什么?
为了给 Vue 提供提示,以便它能够跟踪每个节点的身份,从而重用和重新排列现有元素,你需要为每个项目提供一个唯一的 key 属性。
我建议您永远不要使用index作为键属性,而应该始终使用唯一 ID。解释起来并不复杂,想象一下一个包含 1000 个元素的数组,如果您删除第二个元素,则length迭代数组的索引将发生改变,所有元素的索引都会改变,因此所有组件都会重新加载!
如果使用唯一的 id 来标识项目,并且删除了第二个项目,则另一个组件不会重新加载,因为键的所有信息都没有改变!
v-for 与 v-if
绝对不能同时使用v-for`with` v-if,因为当它们存在于同一个节点上时,`with` 的v-for优先级高于 `with` v-if。这意味着 `with`v-if会在循环的每次迭代中单独运行!
我们来看一个例子!
<template>
<div>
<div
v-for="item in numberList"
v-if="isEven(item)"
:key="item"
>
{{ item }}
</div>
</div>
</template>
<script>
import Vue from "vue"
export default Vue.extend({
data() {
return {
numberList: [ 1, 2, 3, 4, 5, 6 ],
}
},
methods: {
isEven(item) {
return item % 2 === 1
},
},
})
</script>
每次迭代我们都会执行该isEven函数!
如何避免这种情况?
根据具体情况,有两种解决方案:
第一的
我们需要过滤数组中的一些值!
使用computed属性并对其进行迭代!
<template>
<div>
<div
v-for="evenItem in evenList"
:key="evenItem"
>
{{ evenItem }}
</div>
</div>
</template>
<script>
import Vue from "vue"
export default Vue.extend({
data() {
return {
numberList: [ 1, 2, 3, 4, 5, 6 ],
}
},
computed: {
evenList() {
return this.numberList.filter(item => this.isEven(item))
}
},
methods: {
isEven(item) {
return item % 2 === 0
},
},
})
</script>
这里我们在遍历数组之前对其进行过滤!我们不需要使用v-if!
第二
例如,我需要只在数组大小等于 5 时才显示这些项。
你只需再加一个信笺包起来v-for,它就能把信笺包住v-if!
<template>
<div>
<div v-if="numberList.length === 5" >
<div
v-for="item in numberList"
:key="item"
>
{{ item }}
</div>
</div>
</div>
</template>
结论
v-for用于显示数组或对象键,需要始终使用唯一的 id 作为key属性。
永远不要使用v-forwith v-if,根据当前上下文,您还有其他选择!
希望您喜欢这篇文章!
🎁 如果你在推特上关注我并私信我,就可以Underrated skills in javascript, make the difference免费获得我的新书哦😁
或者点击这里获取。
☕️ 您可以支持我的作品🙏
🏃♂️ 你可以关注我 👇
🕊 Twitter:https://twitter.com/code__oz
👨💻 Github:https://github.com/Code-Oz
您可以收藏这篇文章!
文章来源:https://dev.to/codeoz/vue-academy-4-v-for-directive-4l7k