美文网首页
vue2 页面不重新渲染

vue2 页面不重新渲染

作者: 暴躁程序员 | 来源:发表于2023-04-10 16:25 被阅读0次

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>

相关文章

网友评论

      本文标题:vue2 页面不重新渲染

      本文链接:https://www.haomeiwen.com/subject/ghkwddtx.html