【问题标题】:Vue deep cloning props in data is not responsive数据中的Vue深度克隆道具没有响应
【发布时间】:2020-05-02 01:39:28
【问题描述】:

所以我的子组件中有以下代码

   props: {
        prop_accounts: Array,
        prop_pushing_destination: String,
        prop_selected_account: String,
        prop_selected: Boolean,
        shop_settings: Object,
        name_of_selected_account_field: String
    },

    data() {
        return {
            accounts: this._.cloneDeep(this.prop_accounts),
            pushing_destination: this._.cloneDeep(this.prop_pushing_destination),
            selected_account: this._.cloneDeep(this.prop_selected_account),
            selected: this._.cloneDeep(this.prop_selected)
        }
    },

父道具传递所有道具和所有接缝以正常工作,但父道具不断对后端进行采样以进行更改,如果他们获取它,则会更新子道具,尽管我可以看到道具已更改,但数据保持不变现在,如果我直接抛出数据并使用道具一切正常,但我收到以下警告

避免直接修改 prop,因为每当父组件重新渲染时,该值都会被覆盖。相反,使用基于道具值的数据或计算属性。正在变异的道具:“selected_account”

【问题讨论】:

  • 你到底想在这里做什么?这些值是如何使用的?我想不出你需要深度克隆道具的任何充分理由。
  • props 是组件的初始数据,可以更改此数据,例如可以更改所选帐户。自从改变以来,道具就是一种我正在克隆它们的蚂蚁模式

标签: vue.js


【解决方案1】:

有两种方法可以处理这个问题:直接使用 props 并向父级发出更改;或使用计算属性根据数据和道具计算值。

发出更改可能是 99% 的情况下您想要做的事情,因为对内部或外部 props 的任何更改都会改变您的组件正在执行的操作。使用计算的 props 允许仅在内部未修改数据时才使用对 props 的更改。

计算道具

props: {
    defaultAccounts: Array,
    defaultSelected: Boolean,
    ...
}

data: () => ({
    customAccounts: null,
    customSelected: null,
})

computed: {
    accounts() {
        return (this.customAccounts == null) ? this.defaultAccounts : this.customAccounts
    },

    selected() {
        return (this.customSelected == null) ? this.defaultSelected : this.customSelected
    }
}

您甚至可以在计算的 props 上定义 setter 来设置数据属性的值。

发出更改

组件:

props: {
    accounts: Array,
    selected: Boolean,
    ...
}

methods: {
    accountsChanged(value) {
        this.$emit('update:accounts', value)
    },
    selectedChanged(value) {
        this.$emit('update:selected', value)
    }
}

你在哪里使用组件:

<my-component :accounts.sync="accounts" :selected.sync="false"></my-component>

请参阅Sync Modifier Documentation 了解更多信息。

我尚未测试此代码,因此可能需要对其进行调整才能使其正常工作。

【讨论】:

    猜你喜欢
    • 2012-12-25
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多