我开始了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的新手,所以我完全不知道如何修复它。有人知道如何(请解释为什么)解决这个问题吗?


当前回答

我也遇到过这个问题。警告消失后,我使用$on和$emit。 它类似于使用$on和$emit来将数据从子组件发送到父组件。

其他回答

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

不要直接更改组件中的道具。如果你需要改变它,设置一个新的属性,像这样:

data() {
  return {
    listClone: this.list
  }
}

并更改listClone的值。

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

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

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

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

然后你可以用:

$globals.list

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

您需要像这样添加computed方法

component.vue

props: ['list'],
computed: {
    listJson: function(){
        return JSON.parse(this.list);
    }
}

将props分配给new变量。

data () {
    return {
        listClone: this.list
    }
}