问:使用 Vue 3 和 typescript(使用 cli 构建的项目)使 vuex 存储在全球范围内可用 +已解决

Posted

技术标签:

【中文标题】问:使用 Vue 3 和 typescript(使用 cli 构建的项目)使 vuex 存储在全球范围内可用 +已解决【英文标题】:Q: make vuex store globally available with Vue 3 and typescript (project built with the cli) +solved 【发布时间】:2021-12-16 20:18:37 【问题描述】:

如何使用 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')

【问题讨论】:

【参考方案1】:

您需要将商店添加到 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')

【讨论】:

以上是关于问:使用 Vue 3 和 typescript(使用 cli 构建的项目)使 vuex 存储在全球范围内可用 +已解决的主要内容,如果未能解决你的问题,请参考以下文章