我开始了https://laracasts.com/series/learning-vue-step-by-step系列。我在Vue、Laravel和AJAX的课程上停了下来,出现了这个错误:

Vue .js:2574 [Vue警告]:避免直接改变道具,因为每当父组件重新呈现时,该值将被覆盖。相反,应该使用基于道具值的数据或计算属性。道具被突变:"list"(在组件中找到)

我在main.js中有这段代码

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

我知道,当我覆盖列表道具时,问题是在created(),但我是Vue的新手,所以我完全不知道如何修复它。有人知道如何(请解释为什么)解决这个问题吗?


当前回答

道具下降,事件上升。这就是Vue的模式。关键是,如果你试图变异从父母传递的道具。它不会工作,只会被父组件重复覆盖。子组件只能发出一个事件来通知父组件做某事。如果你不喜欢这些限制,你可以使用VUEX(实际上这种模式会吸收复杂的组件结构,你应该使用VUEX!)

其他回答

Vue只是警告您:您更改了组件中的道具,但当父组件重新呈现时,“list”将被覆盖,您将丢失所有更改。所以这样做是危险的。

使用computed属性,如下所示:

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

如果你想改变道具-使用对象。

<component :model="global.price"></component>

组件:

props: ['model'],
methods: {
  changeValue: function() {
    this.model.value = "new value";
  }
}

再加上最好的答案,

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

通过数组设置道具是为了开发/原型,在生产中确保设置道具类型(https://v2.vuejs.org/v2/guide/components-props.html),并设置一个默认值,以防道具没有被父元素填充。

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

这样你至少可以在mutableList中得到一个空对象,而不是JSON。如果未定义,则解析错误。

我个人总是建议,如果你需要改变道具,首先将它们传递给计算属性,然后从那里返回,然后就可以很容易地改变道具,即使在那你也可以跟踪道具的突变,如果它们是从另一个组件中突变的,或者我们也可以观察。

一个潜在的解决方案是使用全局变量。

import { Vue } from "nuxt-property-decorator";

export const globalStore = new Vue({
  data: {
    list: [],
  },
}

export function setupGlobalsStore() {
  Vue.prototype.$globals = globalStore;
}

然后你可以用:

$globals.list

任何你需要变异或呈现它的地方。