1

如何使用 vuex 在 vue 3 中使我的商店在全球范围内可用?

我的店铺:

import { createStore } from 'vuex'

export default createStore({
  state: {},
  mutations: {},
  getters: {},
  actions: {},
  modules: {},
})

我的 main.ts

import yourStore from './store/yourStore'

const app = createApp(App)
app.use(yourStore)

app.config.globalProperties.$yourStore = yourStore

app.mount('#app')

这不起作用:

this.$yourStore.dispatch('your action')
4

1 回答 1

0

您需要将商店添加到 shims-vuex.d.ts 以使其全球可用,如下所示:

import { yourStore } from './store/yourStore' // path to store file

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $yourStore: yourStore
  }
}

现在这有效

this.$yourStore.dispatch('your action')
于 2021-11-02T09:47:42.937 回答