【发布时间】:2018-11-19 23:55:23
【问题描述】:
我想在菜单栏中显示一些数据,这些数据需要远程获取(http get 调用)才能正确显示。当我的应用程序加载时,商店还没有初始化。我应该在哪里做呢?
这就是我现在所拥有的。 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>
商店:
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
}
});
目前命名没有多大意义。但是我需要从菜单组件的 create() 方法中调用“操作”吗?那会有点奇怪。如果我的商店能够以某种方式自行发起初始 http 调用而无需被触发,那就太酷了。我什至不知道如何从 create() 部分调用一个动作。
【问题讨论】:
-
商店创建完成后,只需使用商店的
dispatch方法即可,随时可以使用。如果您愿意,甚至可以在创建 Vue 之前调用它。