版权声明:本文为博主原创文章,转载请注明作者和出处,如有错误,望不吝赐教。 https://blog.csdn.net/weixin_41888813/article/details/82385849
1,文件内容
为item添加不存在的属性,需要使用vue提供的Vue.set( object, key, value )方法。
看详解:https://cn.vuejs.org/v2/api/#Vue-set
这个案例需要注意的一点是:vue 中$index $key 已经移除了
之前可以这样:
<ul id="example">
<li v-for="item in items">
{{$index}}
{{$key}}
</li>
</ul>
现在已经移除,如果还用的话就会报错:Uncaught ReferenceError: $index is not defined;
现在这样写:
<ul id="example">
<li v-for="(item,index) in items">
{{item}}
{{index}}
</li>
</ul>
第一个参数是值,第二个参数是索引;目的是为了保持和原生的一致;
官方文档如是说:
$index and $key 移除 已经移除了 $index 和 $key 这两个隐式声明变量,以便在 v-for 中显式定义。 这可以使没有太多 Vue 开发经验的开发者更好地阅读代码,并且在处理嵌套循环时也能产生更清晰的行为。 升级方式 在代码库中运行迁移工具来找出使用这些移除变量的示例。 如果你没有找到,也可以在控制台错误中查找(例如 Uncaught ReferenceError: $index is not defined)。
这些个新玩意更新很快要时刻关注文档。
案例1:(会有些问题,进不去,如默认第一个,慎用)
<template>
<div>
<ul>
<li v-for="(item,$index) in items" @click="selectStyle (item, $index) " :class="{'active':item.active,'unactive':!item.active}" >
{{item.select}}
<span class="icon" v-show="item.active">当我是图标</span>
</li>
</ul>
</div>
</template>
<script>
import Vue from 'vue'
export default{
data(){
return {
active: false,
items: [
{select:'第一行'},
{select:'第二行'},
{select:'第三行'},
{select:'第四行'}
]
}
},
methods: {
selectStyle (item, index) {
this.$nextTick(function () {
this.items.forEach(function (item) {
Vue.set(item,'active',false);
});
Vue.set(item,'active',true);
});
}
}
}
</script>
<!-- 样式 -->
<style>
.active{
color:red;
}
.unactive{
color:#000;
}
.icon{
float: right;
font-size:12px;
}
</style>
效果
案例2:
https://blog.csdn.net/yibowanbo/article/details/79703575
来源于: