入口文件中,怎么才能及时的拿到vuex中的数据

项目入口文件
app.vue

<script>
.....
create() {
          const that = this;
          that.$store.dispatch('Getsiteinfoactions');
          console.log(that.$store.state.siteinfo);
...........

在VUEX中Getsiteinfoactions是调用接口给siteinfo进行赋值

actions:{
        Getsiteinfoactions(context){
            axios.get('/api/wapinfo/index').then(response => {
                context.commit("Getsiteinfomutations",response.data.data);
            })
        },

axios是一个异步,导致不能及时的把请求到的值赋给siteinfo

有什么办法可以解决这个问题吗?

阅读 2k
3 个回答

要么promise化,要么callback,要么按照loadable思想监听siteinfo
这应该是比较基础的思路吧

思路要更改一下,VUE数据是双向绑定的。
你的state不管是什么时候更新的,只要更新了,那么数据源绑定的地方就一定会触发到。

你可以使用computed, 或者watch都可以解决这个问题

前几年做过一个类似需求的项目,就是一定要在拿到socket连接上,并拿到拿到配置后才实例化vue,我的做法可以参考下,初始化异常的处理代码比较长,代码有删减,意会即可

import Vue from 'vue';
import App from '@/App.vue';
import store from '@/store';
import {Loading, MessageBox, Notification} from 'element-ui';

import {clientConnect} from '@/client/index.js';

const loading = Loading.service({
  fullscreen: true,
  text: '初始化...',
});

clientConnect().then(({SOCKET}) => {
  store.dispatch('systemValidate').then(() => {
    loading.close();
    new Vue({
      render: h => h(App),
      router,
      store
    }).$mount('#app');
  })
})
推荐问题