[英]Vuex4 state populated with api call is undefined in component
Please bare with me I am still new to using Vuex and don't quite understand it yet.请告诉我我对使用 Vuex 还是很陌生,还不太了解。 I am using Vuex4 with localforage package for IndexedDB.
我将 Vuex4 与 localforage package 一起用于 IndexedDB。
My Vuex store is as follows:我的 Vuex 商店如下:
import { createStore } from 'vuex'
import localforage from 'localforage'
import axios from 'axios'
const store = createStore({
state: {
tenantLocale: {}
},
getters: {},
mutations: {
setLocale(state, value) {
state.tenantLocale = value
}
},
actions: {
getTenant(context) {
axios.get('/api/tenant-data/locale').then((response) => {
context.commit('setLocale', response.data)
localforage.setItem('tenantLocale', response.data)
})
}
}
})
export default store
I dispatch the action in my App.vue like this:我在我的 App.vue 中分派操作,如下所示:
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
//get default information about tenant from api
store.dispatch('getTenant')
return {}
}
}
The thing is now if I render the state in my Login.vue component in the template section like so:现在的问题是,如果我在模板部分的 Login.vue 组件中呈现 state,如下所示:
<h1>{{ store.state.tenantLocale.timezone }}</h1>
It shows the correct data, but if I try to do something with it in the script section of my component lets say for example try to print it out:它显示了正确的数据,但是如果我尝试在我的组件的脚本部分中使用它做一些事情,例如尝试打印出来:
console.log(store.state.tenantLocale.timezone)
I get the undefined message.我收到未定义的消息。
What am I missing here?我在这里想念什么? What would be the best approach here?
这里最好的方法是什么? Do I need to create getter for it?
我需要为它创建吸气剂吗? Create a promise?
创建一个 promise? My brain is fried... Any help to at least point me in the right direction is appreciated!
我的大脑被炸了......任何帮助至少将我指向正确的方向表示赞赏!
In setup function you access state or getter with computed:在设置 function 您访问 state 或 getter 计算:
computed(() => store.state.tenantLocale.timezone)
You can do like this你可以这样做
import { computed } from 'vue' import { useStore } from 'vuex' export default { setup () { const store = useStore() return { // access a state in computed function timezone: computed(() => store.state.tenantLocale.timezone), } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.