1. vue2 中通过索引修改数组数据不会重新渲染页面
使用数组方法可重新渲染页面
<template>
<div>
<ul>
<li v-for="item in names" :key="item">{{ item }}</li>
</ul>
<div><button @click="replaceRoles">replace</button></div>
</div>
</template>
<script>
export default {
data() {
return {
names: ['卡罗', '老蔫儿', '贼大胆'],
};
},
methods: {
replaceRoles() {
// this.names[0] = '卡梅利多'; // vue 中无法通过索引重新渲染页面
this.names.splice(0, 1, '卡梅利多'); // 只能通过数组方法改变数据,才可重新渲染页面
},
},
};
</script>
2. vue2 中增加和删除对象的属性不会重新渲染页面
使用 this.$set()、this.$delete()
可重新渲染页面
<template>
<div>
<ul>
<li>{{ userinfo.username }}</li>
<li>{{ userinfo.password }}</li>
</ul>
<div><button @click="deleteInfo">deleteInfo</button></div>
<div><button @click="addInfo">addInfo</button></div>
</div>
</template>
<script>
export default {
data() {
return {
userinfo: {
username: '卡梅利多',
password: '123456',
},
};
},
methods: {
deleteInfo() {
// delete this.userinfo.username; // 对象属性的删除无法重新渲染页面,需要使用 this.$delete()
// console.log(this.userinfo);
this.$delete(this.userinfo, 'username');
},
addInfo() {
// this.userinfo.username = '卡梅利多'; // 对象属性的增加无法重新渲染页面,需要使用 this.$set()
// console.log(this.userinfo);
this.$set(this.userinfo, 'username', '卡梅利多');
},
},
};
</script>
网友评论