Vue中对数组变化监听

在实际开发中,经常要对数组进行操作,最为常见的方法就是直接对数组中的某个元素进行赋值,比如下面这样的:

javascript 复制代码
<script>
    export default {
        data() {
            return {
                comments: [],
                isReply: [0, 0, 0, 0, 0]
            };
        },
        methods: {
            replyTo: function (index) {
                console.log(this.isReply);
                isReply[index] = 1
                console.log(this.isReply);
            }
        },
    };
</script>

但是虽然数组中的元素改变了,但是vue却不能监听到变化,同时引入watch来检测也是没有效果,如下所示

javascript 复制代码
<script>
    export default {
        data() {
            return {
                comments: [],
                isReply: [0, 0, 0, 0, 0]
            };
        },
      watch: {
        isReply: {
          handler(val, oldval) {

          },
          deep: true
        }
      },
        methods: {
            replyTo: function (index) {
                console.log(this.isReply);
                isReply[index] = 1
                console.log(this.isReply);
            }
        },
    };
</script>

从上述例子,发现vue是不会响应数据变化而重新去渲染页面。在vue中仅需要通过修改赋值语句的方式,即可让vue响应数组数据的变化。具体操作如下:

复制代码
// Vue.set
Vue.set(vm.items, indexOfItem, newValue)

// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

具体案例如下

复制代码
<script>
    import Comment from '../components/Comment'

    export default {
        data() {
            return {
                comments: [],
                isReply: [0, 0, 0, 0, 0]
            };
        },
        watch: {

        },
        components: {
            Comment
        },
        methods: {
            replyTo: function (index) {
				
				// 最后一个参数为我们需要改变的值
                this.isReply.splice(index, 1, 1);

                this.$set(this.isReply, index, 1);

            }
        },
    };
</script>
相关推荐
arvin_xiaoting1 小时前
OpenClaw学习总结_I_核心架构_8:SessionPruning详解
前端·chrome·学习·系统架构·ai agent·openclaw·sessionpruning
工程师老罗2 小时前
Image(图像)的用法
java·前端·javascript
早點睡3903 小时前
ReactNative项目OpenHarmony三方库集成实战:react-native-swiper
javascript·react native·react.js
jump_jump3 小时前
深入 JavaScript Iterator Helpers:从 API 到引擎实现
javascript·性能优化
swipe4 小时前
把 JavaScript 原型讲透:从 `[[Prototype]]`、`prototype` 到 `constructor` 的完整心智模型
前端·javascript·面试
问道飞鱼4 小时前
【前端知识】React 组件生命周期:从底层原理到实践场景
前端·react.js·前端框架·生命周期
Dxy12393102164 小时前
JS发送请求的方法详解
开发语言·javascript·ecmascript
CHU7290354 小时前
定制专属美丽时刻:美容预约商城小程序的贴心设计
前端·小程序
浩~~5 小时前
反射型XSS注入
前端·xss
AwesomeDevin5 小时前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构