Vue 2.7 script setup中如何使用VueX 3.6的mapActions?
Vue 2.7 script setup 中 VueX mapActions 报错的解决方法
在 Vue 2.7 的 <script setup> 里直接使用 mapActions 会出现 Cannot read properties of undefined (reading 'dispatch') 错误,原因是 mapActions 生成的函数依赖组件实例的上下文(即 this 指向组件实例,而实例上挂载了 $store),但 <script setup> 中直接调用这些函数时,没有绑定正确的上下文,导致函数内部无法访问到 $store。
以下是两种可行的解决方法:
方法一:直接使用 useStore 获取 store 调用 dispatch(推荐)
这是 <script setup> 中更贴合 Vue 3 风格的写法,也是 Vue 2.7 官方推荐的方式,无需依赖 mapActions:
<script setup> import { useStore } from 'vuex'; import { onMounted } from 'vue'; // 获取 store 实例 const store = useStore(); onMounted(async () => { // 直接调用 dispatch 触发 action await store.dispatch('coupon/fetchCoupons'); }); </script>
方法二:为 mapActions 生成的函数绑定组件上下文
如果坚持要使用 mapActions,需要通过 getCurrentInstance 获取组件实例,把生成的 action 函数绑定到实例上下文上:
<script setup> import { mapActions } from 'vuex'; import { onMounted, getCurrentInstance } from 'vue'; // 获取组件代理实例 const { proxy } = getCurrentInstance(); // 生成 action 映射 const actions = mapActions({ fetchCoupons: 'coupon/fetchCoupons', }); // 为每个 action 函数绑定组件上下文 const boundActions = Object.fromEntries( Object.entries(actions).map(([key, fn]) => [key, fn.bind(proxy)]) ); onMounted(async () => { // 调用绑定后的 action 函数 await boundActions.fetchCoupons(); }); </script>
两种方法都能解决报错问题,优先推荐方法一,写法更简洁且符合 <script setup> 的设计理念。
内容的提问来源于stack exchange,提问作者Md. A. A. Apu
相关产品推荐
相关产品推荐

