vue2中 因响应式原理采用Object.defineProperty数据劫持 导致几种方式改变数据页面 不重新渲染的解决办法

1. vue2 中通过索引修改数组数据不会重新渲染页面

使用数组方法可重新渲染页面

javascript 复制代码
<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() 可重新渲染页面

javascript 复制代码
<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>
相关推荐
kirk_wang16 小时前
Flutter 桌面/Web 开发:用 MouseRegion 打造原生级交互体验
前端·flutter·交互
西洼工作室16 小时前
原生js实现前端国际化
前端·javascript
aha-凯心16 小时前
React 中没有 v-model,如何优雅地处理表单输入
前端·javascript·vue.js·react.js
lcc18716 小时前
Vue3 其它Composition API
前端·vue.js
tsumikistep16 小时前
【前后端】Vue 基本使用方式(下)—— 条件渲染、双向绑定、事件绑定
前端·javascript·vue.js
雨雨雨雨雨别下啦16 小时前
【从0开始学前端】TypeScript语法总结
前端·typescript
敲敲了个代码17 小时前
一天面了6个前端开发,水平真的令人堪忧啊
前端·javascript·学习·面试·webpack·typescript·前端框架
hellotutu17 小时前
vue2+springboot通过 FormData 手动封装图片数据上传
java·vue.js·spring boot·后端·ui
恋猫de小郭17 小时前
用 AI 做了几个超炫酷的 Flutter 动画,同时又差点被 AI 气死
前端·flutter·aigc
十五喵17 小时前
游戏助手|游戏攻略|基于SprinBoot+vue的游戏攻略系统小程序(源码+数据库+文档)
vue.js·游戏·小程序