[英]Vuex4 state populated with api call is undefined in component
請告訴我我對使用 Vuex 還是很陌生,還不太了解。 我將 Vuex4 與 localforage package 一起用於 IndexedDB。
我的 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
我在我的 App.vue 中分派操作,如下所示:
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
//get default information about tenant from api
store.dispatch('getTenant')
return {}
}
}
現在的問題是,如果我在模板部分的 Login.vue 組件中呈現 state,如下所示:
<h1>{{ store.state.tenantLocale.timezone }}</h1>
它顯示了正確的數據,但是如果我嘗試在我的組件的腳本部分中使用它做一些事情,例如嘗試打印出來:
console.log(store.state.tenantLocale.timezone)
我收到未定義的消息。
我在這里想念什么? 這里最好的方法是什么? 我需要為它創建吸氣劑嗎? 創建一個 promise? 我的大腦被炸了......任何幫助至少將我指向正確的方向表示贊賞!
在設置 function 您訪問 state 或 getter 計算:
computed(() => store.state.tenantLocale.timezone)
你可以這樣做
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.