Vue Js 2 提供的无法在 Parent 中更新

问题描述 投票:0回答:1

我正在尝试使用 Vue.js 2.7 中的提供函数,并且我想通过异步函数更新其中一个 props,但它不会更新子项中的注入

Parent.vue

<template>
    <Child />
</template>

<script>
export default {
    provide(){
        return {
            typesTabs: null,
            instanceTypeToAdd: null,
            buttonInstanceTypeToAdd: null,
            updateProvidedPropValue: this.updateProvidedPropValue
        }
    },
    mounted(){
       this.fetchInstances()
    },
    methods: {
        updateProvidedPropValue(propName, value) {
            this[propName] = value
        },
        async fetchInstances() {
            axios.get().then(() => {
                this.typesTabs =
                    JSON.parse(JSON.stringify(res.data.expense_income_type_consts))
            })
        }
    }
}
</script>

Child.vue

<template> 
    <div 
        v-for="tab in typesTabs" 
        @click="updateProvidedPropValue('instanceTypeToAdd', tab)"
    > 
        {{ tab.name }} 
    </div>
</template>

<script>
    export default {
        inject: ['typesTabs', 'instanceTypeToAdd', 'updateProvidedPropValue']
    }
</script>

虽然 updateProvidedPropValue 工作正常,如果我对 typesTabs 对象进行硬编码,但当它异步加载时,typesTabs 不包含任何内容,因此我无法更改 instanceTypeToAdd。

我尝试在 axios 请求之后立即在 Parent.vue 中使用 console.log(this.typesTabs) ,它正确地填充了 prop (typesTabs),但没有更新以在子项中显示内容。

javascript vue.js vuejs2 inject
1个回答
0
投票

来自文档

注意:

provide
inject
绑定不具有反应性。这是故意的。但是,如果您传递一个观察到的对象,该对象上的属性仍然保持反应状态。

您可以将数据和计算属性一起使用作为解决方法

import { computed } from 'vue';

...

provide() {
  return {
    typesTabs: computed(() => this.tabs),
    instanceTypeToAdd: null,
    buttonInstanceTypeToAdd: null,
    updateProvidedPropValue: this.updateProvidedPropValue
  };
},
data() {
  return {
    tabs: []
  };
},
axios.get().then(() => {
  this.tabs =
    JSON.parse(JSON.stringify(res.data.expense_income_type_consts))
})
© www.soinside.com 2019 - 2024. All rights reserved.