v-for循环中key属性的使用

v-for循环中key属性的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.staticfile.org/vue/2.6.10/vue.js"></script>
    <style>


    </style>
</head>
<body>
<div id="app">
    <div>
        <label>Id:
            <input type="text" v-model="id">
        </label>
        <label>Name:
            <input type="text" v-model="name">
        </label>

        <input type="button" value="添加" @click="add">

    </div>
    <!--    注意:v-for循环的时候,key属性只能使用number获取String-->
    <!--    注意:key在使用的时候,必须使用v-bind属性绑定的形式,指定key的值-->
    <!--    在组件中,使用v-for的时候,或者在一些特殊情况中,如果使用v-for有问题,必须在使用v-for的同时,指定唯一的字符串/数字类型:key值-->
    <p v-for="item in list" :key="item"><!--绑定唯一标识符id-->
        <input type="checkbox">
        {{item.id}}--------{{item.name}}
    </p>

</div>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            id: '',
            name: '',
            list: [
                {id: 1, name: 'zs1'},
                {id: 2, name: 'zs2'},
                {id: 3, name: 'zs3'},
                {id: 4, name: 'zs4'}
            ]
        },
        methods: {
            add() {
                this.list.push({id: this.id, name: this.name})
            }
        }
    })
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
v-for循环,如果需要动态绑定class,可以通过computed属性来实现。具体实现方法如下: 1. 首先,在data定义需要绑定的class名称,以及一个包含class名称的数组。 2. 在computed属性使用map方法遍历数据源,根据需要绑定的条件返回class名称,然后将class名称添加到数组。 3. 在v-for循环使用v-bind指令将class绑定到computed属性定义的数组上。 举个例子,假设你有一个数组items,你想要在循环动态绑定class,可以按照以下方法实现: ``` <template> <div v-for="(item, index) in items" :key="index" :class="getClass(index)"> {{ item.name }} </div> </template> <script> export default { data() { return { activeClass: 'active', items: [ { name: 'item1', active: true }, { name: 'item2', active: false }, { name: 'item3', active: true }, { name: 'item4', active: false } ], classes: [] } }, computed: { getClass() { return this.items.map((item, index) => { if (item.active) { return this.activeClass } else { return '' } }) } } } </script> <style> .active { color: red; } </style> ``` 在上面的代码,我们在data定义了需要绑定的class名称activeClass,以及一个包含class名称的数组classes。在computed属性,我们使用map方法遍历数据源items,根据需要绑定的条件返回class名称,然后将class名称添加到classes数组。 在v-for循环,我们使用v-bind指令将class绑定到computed属性定义的数组classes上。这样,当item.active为true时,对应的div元素就会应用active这个class,字体颜色变为红色。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值