Vue 异步调用后将数据传递给 props

Pre*_*obb 2 asynchronous vue.js vue-component

我已经建立了一个简单的 vue 项目来展示这个问题。我唯一添加的是 axios 包。问题是当我尝试在异步调用后设置子组件的属性时,我无法读取组件中的该属性。如果您查看代码,您可以看到我多次控制台日志以显示何时可以获取数据以及何时不能获取数据。请帮我弄清楚我在这里缺少什么。

家长

<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>
Run Code Online (Sandbox Code Playgroud)

孩子

<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>
Run Code Online (Sandbox Code Playgroud)

小智 6

console.log内部创建的挂钩将向您显示父组件中该变量的初始状态。这是因为Parent的created hook和Child的created hook会同时运行。

所以,当你解决你的承诺时,子组件已经创建了。要了解此行为,请使用 将 props 放入模板中{{ this.test_prop }}

要解决这个问题,根据您的需要,您可以为您的 props 定义一些默认值请参阅)或使用v-if条件渲染您的子组件。就是这样,希望有帮助!