Vuex - 何时从 http 服务器加载/初始化存储数据

cod*_*leb 10 vue.js axios vuex vuejs2

我想在菜单栏中显示一些数据,需要远程获取(http get call)才能正确显示。当我的应用程序加载时,商店尚未初始化。我应该在哪里做?

这就是我现在所拥有的。nodeInfo是一个空对象,只要没有获取数据。

导航组件

<template>
  <nav class="navbar" role="navigation" aria-label="main navigation">
    ...
      <div class="navbar-end">
        <span class="navbar-item">
          <div v-if="nodeInfo.latestSolidSubtangleMilestoneIndex">
            {{nodeInfo.latestSolidSubtangleMilestoneIndex}} / {{nodeInfo.latestMilestoneIndex}}
          </div>
          <div v-else>
            Node seems offline!
          </div>
        </span>
      </div>
    </div>
  </nav>
</template>

<script>
  import {mapGetters} from 'vuex';

  export default {
    name: 'Menu',
    computed: {
      ...mapGetters(['nodeInfo']) // Only the getters, no actions called to initialize them.
    }
  };
</script>

<style scoped>

</style>
Run Code Online (Sandbox Code Playgroud)

店铺:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import axios from 'axios';

const iri_ip = '192.168.1.199';
const iri_port = '14265';

const state = {
  token: null,
  loading: false,
  nodeInfo: {}
};

const mutations = {
  SET_NODE_INFO(state, info) {
    state.nodeInfo = info;
  }
};

const actions = {
  fetchNodeInfo({commit}) {
    axios(createIriRequest('getNodeInfo')).then(response => {
      console.log(response.data);
      commit('SET_NODE_INFO', response.data);
    });
  }
};

const getters = {
  token: state => state.token,
  loading: state => state.loading,
  nodeInfo: state => state.nodeInfo
};

const loginModule = {
  state,
  mutations,
  actions,
  getters
};

function createIriRequest(command) {
  return {
    url: `http://${iri_ip}:${iri_port}`,
    data: {'command': command},
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      'X-IOTA-API-Version': '1'
    }
  };
}

export default new Vuex.Store({
  modules: {
    loginModule
  }
});
Run Code Online (Sandbox Code Playgroud)

命名目前没有多大意义。但是我是否需要从菜单组件的 create() 方法中调用“动作”?那会有点奇怪。如果我的商店能够以某种方式在不需要触发的情况下自行进行初始 http 调用,那就太酷了。我什至不知道如何从 create() 部分调用一个动作。

小智 9

在此处查看 vue.js 生命周期图:https ://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram并在此处阅读生命周期挂钩:https ://vuejs.org/v2/ guide/instance.html#Instance-Lifecycle-Hooks。它将大大帮助您了解何时何地添加商店调度方法。this.$store.dispatch('fetchNodeInfo')

简而言之:

  • Created hook:实例已创建,所有数据观察、计算属性、方法、观察/事件回调均已设置,但 $el 属性尚不可用。

  • 挂载钩子:Vue 实例已经挂载,其中 el 替换为新创建的 vm.$el。el 是通过 new Vue({...}) 创建的实例。

为了您的阅读乐趣:


cod*_*leb 4

@Bert 是对的。我将调度方法添加到组件的created()方法中。

export default {
    name: 'Menu',
    created() {
      this.$store.dispatch('fetchNodeInfo');
    },
...
}
Run Code Online (Sandbox Code Playgroud)