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


当前回答

当TypeScript是你的首选lang。的发展

<template>
<span class="someClassName">
      {{feesInLocale}}
</span>
</template>  



@Prop({default: 0}) fees: any;

// computed are declared with get before a function
get feesInLocale() {
    return this.fees;
}

而不是

<template>
<span class="someClassName">
      {{feesInLocale}}
</span>
</template>  



@Prop() fees: any = 0;
get feesInLocale() {
    return this.fees;
}

其他回答

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

使用computed属性,如下所示:

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

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

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

并更改listClone的值。

这与这样一个事实有关:在Vue 2中,局部变异道具被认为是一种反模式

你现在应该做的是,如果你想在本地改变一个道具,在你的数据中声明一个字段,使用props值作为它的初始值,然后改变副本:

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

你可以在Vue.js官方指南上阅读更多相关内容


注1:请注意,您的道具和数据不应使用相同的名称,即:

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

注2:因为我觉得有一些关于道具和反应性的困惑,我建议你看看这个帖子

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

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

组件:

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

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

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

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

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

然后你可以用:

$globals.list

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