为什么 Vue.js 允许推送到 prop 数组? [英] Why does Vue.js allow pushing to prop array?

查看:29
本文介绍了为什么 Vue.js 允许推送到 prop 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们尝试直接更改 prop 值时,Vue.js 会显示警告,如下所示:

Vue.component('游戏', {模板:`<div><ol><li v-for="game in games">{{ game }}</li></ol><button @click="clear">清除游戏</button>

`,道具:['游戏'],方法: {清除:函数(){this.games = [];}}});

显示的警告是:

<块引用>

避免直接改变 prop,因为每当父组件重新渲染时,该值将被覆盖.相反,使用基于 prop 的值的数据或计算属性.

我知道为什么会发生这种情况,但令我惊讶的是 .push() 不会发生这种情况.如果我更改方法以向数组添加值而不是重写它,则不会发出警告:

方法:{添加:函数(){this.games.push('随便');}}

为什么没有警告?如何直接推送到 prop 很好而重写不是?

解决方案

这只是因为 Array 是一种引用内存.当您将 ArrayObject 存储在任何变量中时,它就是一个引用变量.

Memory management 在这种情况下,引用变量将指向heap 中的一个内存地址,因此您可以向地址添加更多 n 个值.但是,即使使用新地址,您也不能仅用任何新值替换该地址.

Vue.js displays warning when we try to change the prop value directly, like this:

Vue.component('Games', {
    template: `
        <div>
            <ol>
                <li v-for="game in games">{{ game }}</li>
            </ol>
            <button @click="clear">Clear games</button>
        </div>
    `,
    props: ['games'],
    methods: {
        clear: function () {
            this.games = [];
        }
    }
});

The warning being displayed is:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.

I know why that happens, but what I find surprising is that it doesn't happen with .push(). If I change the method to add a value to the array instead of rewriting it, there's no warning:

methods: {
    add: function () {
        this.games.push('Whatever');
    }
}

Why is there no warning? How is pushing directly to the prop fine and rewriting is not?

解决方案

It's just because Array is kind of reference memory. When you have Array or Object stored in any variable it's a reference variable.

Memory management in such case, The reference variable will points to a memory address in heap so you can add more n more value to address. However you cannot just replace that address with any new value even with the new address.

这篇关于为什么 Vue.js 允许推送到 prop 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆