Quasar(Vue3+Vuex4)环境下单文件组件如何访问Vuex store?
解决方案
1. 修复setup中useStore()无法获取实例的问题
你注册store时传入了自定义storeKey,Vuex默认的useStore()会读取默认注入键,和你注册的键不匹配才会报"injection 'store' not found"。
修改方法:调用useStore时传入和注册时完全一致的storeKey即可:
// 先引入你注册store时用的同一个storeKey import { storeKey } from '你的store配置文件路径' import { useStore } from 'vuex' setup () { const $store = useStore(storeKey) // 传入自定义key // 后续可以正常调用store方法 const loggedIn = computed({ get: () => $store.state.auth.loggedIn, set: () => { $store.commit('login') } }) // 调用dispatch也直接使用$store实例即可 const handleLogin = () => { $store.dispatch('auth/loginAction', { /* 传参 */ }) } return { loggedIn, handleLogin } }
2. 修复选项式API中this.$store的类型报错
这是TypeScript类型声明缺失导致的,你需要在项目的类型声明文件(一般是src目录下的env.d.ts或者自定义的vuex.d.ts)中扩展Vue的ComponentCustomProperties类型:
// src/vuex.d.ts import { ComponentCustomProperties } from 'vue' import { Store } from 'vuex' // 替换成你自己的State类型定义 type State = { auth: { loggedIn: boolean } } declare module '@vue/runtime-core' { interface ComponentCustomProperties { $store: Store<State> } }
添加完声明后,选项式API中就可以正常访问this.$store.state、this.$store.commit、this.$store.dispatch了。
补充:配合映射函数使用
如果习惯用Vuex的映射工具,也可以结合mapMutations、mapActions直接把方法挂载到组件实例上,用法和你之前用的mapState一致:
import { mapMutations, mapActions } from 'vuex' export default { methods: { ...mapMutations(['login']), // 映射后直接调用this.login()即可触发commit ...mapActions(['auth/loginAction']), // 支持命名空间写法 handleSubmit() { this.login() // 命名空间方法调用:this['auth/loginAction']() } } }
内容的提问来源于stack exchange,提问作者Joshua Ohana
相关产品推荐
相关产品推荐

