【发布时间】:2020-10-13 22:02:24
【问题描述】:
我遇到了从商店中获取空值的问题...有时,并且仅在某些值上。如果有人能指出我正确的方向并解释为什么它是错误的......我将非常感激。所以这是我的store.getters.getApiKey 有时是"" 有时不是。
所以……在下面的组件vue中,第一次引用时不为null
{{this.$store.getters.getApiKey}}
然后在已安装的部分中,设置了store.getters.getHostUrl,但store.getters.getApiKey 不断返回""。
以下是详细信息:
组件.vue
<template>
<div class="countryCodes">
<p>ApiKey : {{this.$store.getters.getApiKey}}</p>
<p>CountryCode Data is {{ page }}</p>
<div class="CountryCodes">
<tr v-for="ccdata in content_list" v-bind:key="ccdata.guid">
<td>{{ ccdata.guid }}</td>
<td>{{ ccdata.name }}</td>
<td>{{ ccdata.code }}</td>
</tr>
</div>
</div>
</template>
import axios from "axios";
import store from "@/store";
export default {
name: 'CountryCodes',
data () {
return {
page: "",
content_list: []
}
},
mounted () {
axios({ method: "GET", "url": store.getters.getHostUrl + "
"/api/"+store.getters.getApiKey+"/countryCodes" }).then(result => {
this.page = result.data.page;
this.content_list = result.data.contents;
}, error => {
console.error(error);
});
},
methods: {
}
}
</script>
然后我的商店(store.js)看起来像这样......
import Vuex from "vuex";
import Vue from 'vue';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
apiKey: "",
hostUrl:""
},
mutations: {
SET_APIKEY(state, value) { state.apiKey = value; },
SET_HOST_URL(state, value) {state.hostUrl = value; }
},
getters: {
getApiKey(state) { return state.apiKey; },
getHostUrl(state) { return state.hostUrl; }
}
})
最后在我的 main.js 中,我将数据提交到存储区...:
import Vue from 'vue'
import App from './App.vue'
import router from './router/index.js'
import store from './store.js'
new Vue({
el: '#app',
render: h => h(App),
router,
store,
mounted: function() {
console.log(this.$route.query)
store.commit('SET_APIKEY', this.$route.query.api)
store.commit("SET_HOST_URL", location.origin.toString())
}
})
我在尝试构建 http 服务时遇到了同样的问题,其中 apikey 的 store 为空。我错过了什么魔法?
【问题讨论】:
-
让我添加一个细节。我认为这是一个时间问题。数据显示在我进入应用程序的第一条路线上。如果我导航到不同的路线,然后返回,这些值将被正确设置。也许我需要添加一块手表?
-
我在
beforeCreate()初始化我的商店
标签: javascript vue.js vuejs2 vuex