繁体   English   中英

Vuex4 state 填充了 api 调用在组件中未定义

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM