在Nuxt中结合@vue/composition-api在setup函数中使用$store.commit
在@vue/composition-api的setup中使用Vuex的store并调用commit方法
针对@vue/composition-api不支持useStore的情况,你可以通过以下两种方式在setup函数中获取store并调用commit方法:
方法一:通过setup的context参数获取根实例的$store
在Vue2的composition-api中,setup函数的第二个参数是context对象,其中root属性指向Vue根实例,而根实例上已挂载了配置好的Vuex store,直接取用即可:
<template> <div> <h1>Vuex Typescript Test</h1> <button @click="handleLogin">click</button> </div> </template> <script lang="ts"> import { defineComponent } from '@vue/composition-api' export default defineComponent({ setup(props, context) { // 从根实例获取store const store = context.root.$store const handleLogin = () => { // 调用commit提交mutation store.commit('login/doLogin', { username: 'test', password: '123456' }) } return { handleLogin } }, }) </script>
方法二:通过getCurrentInstance获取组件实例获取$store
如果不想依赖context传递,也可以用getCurrentInstance获取当前组件实例,再从实例的proxy或root属性中拿到store:
<template> <div> <h1>Vuex Typescript Test</h1> <button @click="handleLogin">click</button> </div> </template> <script lang="ts"> import { defineComponent, getCurrentInstance } from '@vue/composition-api' export default defineComponent({ setup() { const instance = getCurrentInstance() if (!instance) throw new Error('组件实例获取失败') // 从组件实例的proxy中获取store const store = instance.proxy?.$store if (!store) throw new Error('未找到Vuex store实例') const handleLogin = () => { store.commit('login/doLogin', { username: 'test', password: '123456' }) } return { handleLogin } }, }) </script>
额外提示(TypeScript类型优化)
为了避免类型报错,可以在项目中添加Vuex类型声明文件(比如src/vuex.d.ts):
import { Store } from 'vuex' // 导入你的根state类型 import { RootState } from './store' declare module '@vue/composition-api' { interface ComponentCustomProperties { $store: Store<RootState> } }
内容的提问来源于stack exchange,提问作者JinSub
相关产品推荐
相关产品推荐

