vue.js 异步组件中异步响应数据的使用

icomxhvb  于 12个月前  发布在  Vue.js
关注(0)|答案(1)|浏览(142)

下面是父零部件和子零部件:

export default {
    name : 'parentNode',
    mounted: function () {
        var that = this;

        if (that.$store.state.auth.isAuthenticated) {
        
            that.$store.dispatch(ActionsType.GET_ALLCOINLIST).then(function (data) {
            // I want to use this store data in child components.
                that.$store.state.main.data = data;
            });
        }
    },
};

export default {
    name : 'childNode',
    data : function(){
        return {
            childData : {}
        }
    },
    mounted : function(){
        //How should I check if the data is loaded or not?
    },
    computed : {
        childData : function(){
            return this.$store.state.main.data;
        }
    },
    watch : {
        childData : function(){
            this.makeChart();
        }
    },
    methods : {
        makeChart : function(){
            console.log('this function make a chart.');
        }
    }
}

字符串
每当$store(vuex)数据发生变化时,我想绘制一个新的图表。然而,由于此数据的响应是异步的,当子组件加载时,它可能已经接收到数据(在父组件中),也可能没有。
我总是想用最初加载子组件时收到的数据绘制一个图表。Vue的组件也是异步加载的,那么在这种情况下,我如何控制呢?截至目前,如果最初加载子组件,可能会绘制图表,也可能不会。

6ie5vjzr

6ie5vjzr1#

可以使用mapState()watch()

import Vue from "https://cdn.skypack.dev/[email protected]";
import * as vuex from "https://cdn.skypack.dev/[email protected]";

Vue.use(vuex)

var store = new vuex.Store({
  state: {
    count: 1,
    isLoaded: false, // mutate that when async call is finished
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    init() {
      setInterval(() => this.commit('increment'), 1000) // replace this with async call and mutate isLoaded in then()
    }
  }
});

var app = new Vue({
  el: '#app',
  store,
  data() {
    return {
    }
  }, computed: {
    ...vuex.mapState([
      'count'
    ]),
  },
    watch: {
      count() {
        console.log('watch count', this.count)
      }
    },
  mounted() {
    this.$store.dispatch('init')
  }
})

字符串

相关问题