0

请告诉我我对使用 Vuex 还是很陌生,还不太了解。我正在为 IndexedDB 使用带有 localforage 包的 Vuex4。

我的 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 组件中呈现状态,如下所示:

<h1>{{ store.state.tenantLocale.timezone }}</h1>

它显示了正确的数据,但是如果我尝试在我的组件的脚本部分中使用它做一些事情,例如尝试打印出来:

console.log(store.state.tenantLocale.timezone)

我收到未定义的消息。

我在这里想念什么?这里最好的方法是什么?我需要为它创建吸气剂吗?创建一个承诺?我的大脑被炸了......任何帮助至少将我指向正确的方向表示赞赏!

4

2 回答 2

0

在 setup 函数中,您可以使用 computed 访问 state 或 getter:

computed(() => store.state.tenantLocale.timezone)
于 2022-01-06T18:17:01.593 回答
0

你可以这样做

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),

    }
  }
}

于 2022-01-06T19:26:34.940 回答