首页 > 解决方案 > Vue.JS 不会将数据更新到嵌套组件中

问题描述

我正在使用 3 个 VUE 嵌套组件(主组件、父组件和子组件),但在传递数据时遇到了问题。

主要组件使用基于输入请求获取简单的 API 数据:结果用于获取其他组件中的其他信息。

例如,第一个 API 返回区域“DE”,填充第一个组件,然后尝试从区域“DE”获取“食谱”,但出现问题:控制台中的调试注释顺序错误,使用的变量结果为空第二个请求(步骤 3):

  app.js:2878 Step_1: DE 
  app.js:3114 Step_3:  0
  app.js:2890 Step_2: DE

这是父(包含在主要组件中)代码:

父模板

<template>
   <div>
       <recipes :region="region"/>
   </div>
</template>

父代码

 data: function () {
        return {
            region: null,
        }
    },

 beforeRouteEnter(to, from, next) {

        getData(to.params.e_title, (err, data) => {
           
             console.log("Step_1: "+data.region); // return  Step_1: DE

             // here I ned to update the region value to "DE"
           
            next(vm => vm.setRegionData(err, data));
        });
    },

    methods: {
        setRegionData(err, data) {
            if (err) {
                this.error = err.toString();
            } else {
                console.log("Step_2: " + data.region); // return DE
                this.region = data.region;
                
            }
        }
    },

子模板

<template>
     <div v-if="recipes" class="content">
      <div class="row">
            <recipe-comp v-for="(recipe, index) in recipes" :key="index" :title="recipe.title" :vote="recipe.votes">
    </recipe-comp>
        </div>
       </div>
     </template>

子代码

props: ['region'],
....
 beforeMount () {
        console.log("Step_3 "+this.region); // Return null!!
        this.fetchData()
    },

我认为问题应该是父beforeRouteEnter钩子。

重要的调试说明:

1)看起来子代码工作正常,因为如果我将父数据中的默认值替换为“IT”而不是null,则子组件会从第二个 API 请求返回正确的配方。这证实了默认数据更新得太晚,而不是在它从第一个 API 请求获得结果时更新。

data: function () {
    return {
        region: 'IT',
    }
},

2)如果我在子模板中使用 {{region}} 它会显示正确(和更新的)数据:'DE'!

我需要新鲜的眼睛来修复它。你能帮助我吗?

标签: laravelvue.js

解决方案


beforeMount您应该能够使用该watch属性来完成此操作,而不是使用子组件内部的钩子。我相信这是因为在beforeMount父级能够设置该属性之前触发了钩子。



简而言之,您可以尝试更改此设置:

props: ['region'],
....
 beforeMount () {
    console.log("Step_3 "+this.region); // Return null!!
    this.fetchData()
},

对于这样的事情:

props: ['region'],
....
 watch: {
    region() {
        console.log("Step_3 "+this.region); // Return null!!
        this.fetchData()
    }
},

干杯!!


推荐阅读