laravel - Vue.JS 不将数据更新到嵌套组件中

标签 laravel 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 Hook 中。

重要调试说明:

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

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

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

我需要新的眼光来解决它。你能帮我吗?

最佳答案

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



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

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()
    }
},

干杯!!

关于laravel - Vue.JS 不将数据更新到嵌套组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56201752/

相关文章:

php - 将多个站点添加到 laravel homestead,但第一个站点出现在两个域中

laravel - 如何使用 Mailgun 和 Laravel 发送电子邮件?

laravel - 从 Laravel 4.1 直接升级到 Laravel 5.3

javascript - 路由嵌套数组后Vue js不渲染

jquery - VueJS : Fire jQuery after v-for?

javascript - 样式绑定(bind)中的数据未更新(Vue)

php - Laravel LeftJoin where

php - 在 laravel Controller 中处理从 mysql 存储过程接收的数组

javascript - 本地 laravel API 上的 Nativescript-Vue axios 调用错误 [请求失败,状态码为空]

javascript - 如何在 Vue.js 中的对象字段上使用 v-for 时打印索引?