在Vue中进行异步调用后将数据传递给道具 [英] Passing data to props after asynchronous call in Vue

查看:79
本文介绍了在Vue中进行异步调用后将数据传递给道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个简单的Vue项目来显示问题.我添加的唯一一件事是axios软件包.问题是,当我尝试在异步调用后设置子组件的属性时,无法在组件中读取该属性.如果看一下代码,您会看到我多次控制台日志,以显示何时可以获取数据以及何时无法获取数据.请帮助我找出这里缺少的内容.

I have set up a bare bones vue project to show the problem. The only thing I added was the axios package. The problem is when I try to set the property of child component after an asynchronous call I cant read that property in the component. If you look at the code you can see I console log several times to show when I can get the data and when I cant. Please help me figure out what im missing here.

父母

<template>
  <div id="app">
    <HelloWorld :test_prop="testData" :test_prop2="testData2" :test_prop3="testData3" test_prop4="I work also"/>
    <div>{{testData5}}</div>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import axios from 'axios';
export default {
  name: 'app',
  components: {
    HelloWorld
  },
  data() {
    return {
      testData: '',
      testData2: 'I work just fine',
      testData3: '',
      testData5: ''
    }
  },
  created: function(){
    var self = this;
    this.testDate3 = 'I dont work';
    axios.get('https://jsonplaceholder.typicode.com/posts/42').then(function(response){
      //I need this one to work
      self.testData = 'I dont work either';

      self.testData5 = 'I work also';
    });
  }
}
</script>

孩子

<template>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: ['test_prop', 'test_prop2', 'test_prop3', 'test_prop4'],
  data() {
    return {
      comp_data: this.test_prop,
      comp_data2: this.test_prop2,
      comp_data3: this.test_prop3,
      comp_data4: this.test_prop4
    }
  },
  created: function(){
    console.log(this.test_prop);
    console.log(this.test_prop2);
    console.log(this.test_prop3);
    console.log(this.test_prop4);
  }
}
</script>

在创建的钩子中的

推荐答案

您的 console.log 会向您显示Parent组件中此变量的初始状态.这是因为父级创建的钩子和子级创建的钩子将同时运行.

Your console.log inside created hook will show you the initial state of this variables in Parent component. That's because Parent's created hook and Child's created hook will run at the same time.

因此,当您实现诺言时,就已经创建了子组件.要了解这种行为,请使用 {{this.test_prop}} 将道具放在模板中.

So, when you solve your promise, Child component was already created. To understand this behavior, put your props in your template using {{ this.test_prop }}.

要解决此问题,您可以根据自己的需要定义一些默认值作为道具( v-if 条件.就是这样,希望对您有所帮助!

To solve it, depending on what you want, you can either define some default value to your props (see) or render your child component with a v-if condition. That's it, hope it helps!

这篇关于在Vue中进行异步调用后将数据传递给道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆