asynchronous - 在 Vue 中异步调用后将数据传递给 Prop

标签 asynchronous vue.js vue-component

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

parent

<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>

child

<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>

最佳答案

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

因此,当您解决您的 promise 时,子组件已经创建。要了解此行为,请使用 {{ this.test_prop }} 将 Prop 放入模板中。

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

关于asynchronous - 在 Vue 中异步调用后将数据传递给 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55515479/

相关文章:

python - 在 BigQuery 中运行异步查询并没有明显加快

android - 同步和异步 Activity

Javascript 阻塞直到图像预加载完成?

javascript - Vue.JS - 类型错误 : Cannot use 'in' operator to search for 'undefined' in Laravel Object

javascript - 使用方法获取数组以使用 V-for 循环进行迭代,但没有显示任何内容

javascript - v-html 中的 Vue.js v-model

node.js - Vue JS Intellij 设置

c# - 调用套接字的ReceiveAsync()调用后,接收到的数据缓冲区始终为空吗?

vue.js - Vue 和 Vuex v-for 状态改变时不能正常更新

javascript - 'this.$refs' 在父组件中始终为空