You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Vue CLI搭建的Vue3+TypeScript项目如何让Vuex Store全局可用【已解决】

配置不生效原因

  • Vue3 执行 app.use(store) 注册 Vuex 后,会默认将 store 实例绑定到全局属性 $store 上,你额外手动挂载的 $yourStore 没有和 Vue 响应式系统完全绑定,导致调用方法不生效
  • 如果你是在组合式 API 的 setup 语法中调用 this,setup 本身不存在 this 指向,自然无法获取到挂载的全局属性

正确全局配置步骤

1. Store 定义

你的现有 store 定义逻辑无需修改,示例如下(可根据业务补全逻辑):

// src/store/yourStore.ts
import { createStore } from 'vuex'

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

2. main.ts 注册配置

移除手动挂载 $yourStore 的代码,简化注册逻辑即可:

import { createApp } from 'vue'
import App from './App.vue'
import yourStore from './store/yourStore' // 对应你自己的store文件路径

const app = createApp(App)
app.use(yourStore) // 注册后默认全局挂载 $store 属性

app.mount('#app')

如果你确实需要自定义全局 store 的调用名称(比如保留 $yourStore 命名),可以补充以下配置:

// main.ts app.use(yourStore) 之后添加
app.config.globalProperties.$yourStore = app.config.globalProperties.$store

全局调用方法

选项式 API 组件中调用

直接通过默认挂载的$store调用,或者你自定义的$yourStore调用:

export default {
  methods: {
    testDispatch() {
      // 默认挂载的调用方式
      this.$store.dispatch('你的action名称')
      // 自定义命名的调用方式
      // this.$yourStore.dispatch('你的action名称')
    }
  }
}

组合式 API 组件中调用

组合式 API 无this指向,需要用 Vuex 官方提供的useStore方法获取实例:

<script setup lang="ts">
import { useStore } from 'vuex'

const store = useStore()
const testDispatch = () => {
  store.dispatch('你的action名称')
}
</script>

内容的提问来源于stack exchange,提问作者Mara Omisha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:54:00