Vue 2 - 改变道具 vue-warn [英] Vue 2 - Mutating props vue-warn

查看:23
本文介绍了Vue 2 - 改变道具 vue-warn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始了https://laracasts.com/series/learning-vue-分步系列.我在Vue、Laravel 和 AJAX 课上停了下来,遇到了这个错误:

I started https://laracasts.com/series/learning-vue-step-by-step series. I stopped on the lesson Vue, Laravel, and AJAX with this error:

vue.js:2574 [Vue 警告]:避免直接改变 prop,因为每当父组件重新渲染时,该值将被覆盖.相反,根据道具的值使用数据或计算属性.道具正在发生变化:列表"(在组件中找到)

vue.js:2574 [Vue warn]: 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. Prop being mutated: "list" (found in component )

我在 ma​​in.js

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    created() {
        this.list = JSON.parse(this.list);
    }
});
new Vue({
    el: '.container'
})

当我覆盖列表道具时,我知道问题出在 created() 中,但我是 Vue 的新手,所以我完全不知道如何解决它.任何人都知道如何(并请解释原因)修复它?

I know that the problem is in created() when I overwrite the list prop, but I am a newbie in Vue, so I totally don't know how to fix it. Anyone have an idea how (and please explain why) to fix it?

推荐答案

这与 在本地改变 prop 被认为是 Vue 2 中的反模式

如果你想在本地改变一个 prop,你现在应该做的是在你的 data 中声明一个使用 props value 作为它的初始值,然后改变副本:

What you should do now, in case you want to mutate a prop locally, is to declare a field in your data that uses the props value as its initial value and then mutate the copy:

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    data: function () {
        return {
            mutableList: JSON.parse(this.list);
        }
    }
});

您可以在 Vue.js 上阅读更多相关信息官方指南

注意 1:请注意你应该不要为你的propdata,即:

data: function () { return { list: JSON.parse(this.list) } } // WRONG!!

注 2: 由于 我觉得关于propsreactivity 有一些困惑,我建议你看看这个线程

Note 2: Since I feel there is some confusion regarding props and reactivity, I suggest you to have a look on this thread

这篇关于Vue 2 - 改变道具 vue-warn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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