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

问题描述 投票:0回答:1

下面是父组件和子组件:

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的组件也是异步加载的,那么这种情况下,我该如何控制呢?截至目前,如果子组件最初加载,则可能会也可能不会绘制图表。

javascript vue.js asynchronous vue-component
1个回答
1
投票

您可以使用

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')
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.