Vue.set 的作用就是在构造器外部操作构造器内部的数据、属性或者方法。我们可以通过原生js对数据进行操作,但是当只通过索引操作数组时,就展现出vue.set的价值了。接下来看一下代码显示:
<div id="app">
<p>{{name}}-{{age}}</p>
<ul>
<li v-for="(item, index) in hobby" :key="index">{{item}}</li>
</ul>
<button type="button" @click="innerAlter">改变值</button>
</div>
var outData={
name:"小明",
age:12,
hobby:["baseball","basketball","football"]
};
var vm=new Vue({
el:"#app",
data:outData,
methods: {
innerAlter:function(){
this.name="小红";
this.hobby[0]="reading";
console.log(this.name);
console.log(this.hobby);
}
}
})
点击按钮,会出现下面结果,我们发现未使用vue.set,我们的页面也检测到数据改变并显示跟新后的数据;
注意:下面的js代码,我们去除name的改变值代码
var outData={
name:"小明",
age:12,
hobby:["baseball","basketball","football"]
};
var vm=new Vue({
el:"#app",
data:outData,
methods: {
innerAlter:function(){
//this.name="小红";
this.hobby[0]="reading";
console.log(this.name);
console.log(this.hobby);
}
}
})
页面没有检测到数组的跟新,实际上数组的值已经改变。这就是当我们在只通过索引改变数组的数据时,页面是无法检测到数据跟新的。
var outData={
name:"小明",
age:12,
hobby:["baseball","basketball","football"]
};
var vm=new Vue({
el:"#app",
data:outData,
methods: {
innerAlter:function(){
Vue.set(this.hobby, 0, "reading")
//console.log(this.name);
console.log(this.hobby);
}
}
})
通过上面代码展示应该可以理解Vue.set的作用了吧。
当然Vue.set也可以改变数组的长度,可以增加;
var outData={
name:"小明",
age:12,
hobby:["baseball","basketball","football"]
};
var vm=new Vue({
el:"#app",
data:outData,
methods: {
innerAlter:function(){
Vue.set(this.hobby, this.hobby.length, "reading")
//console.log(this.name);
console.log(this.hobby);
//
}
}
})
如果要删除某一项;
var outData={
name:"小明",
age:12,
hobby:["baseball","basketball","football"]
};
var vm=new Vue({
el:"#app",
data:outData,
methods: {
innerAlter:function(){
//Vue.set(this.hobby, this.hobby.length, "reading")
this.hobby.splice(1,1);
console.log(this.hobby);
//
}
}
})