mapActions ,组合式API的写法,给个例子
时间: 2024-03-06 20:50:22 浏览: 19
在 Vue3 中,使用组合式 API 时,可以通过使用 `useStore` 和 `mapActions` 函数来将 store 中的 actions 映射到组件中。下面是一个使用组合式 API 的示例:
```javascript
import { useStore } from 'vuex'
import { mapActions } from 'vuex'
export default {
setup() {
const store = useStore()
const { increment, decrement } = mapActions('moduleA', ['increment', 'decrement'])
return {
increment,
decrement
}
}
}
```
上述代码中,我们首先使用 `useStore` 函数获取 store 实例,然后使用 `mapActions` 函数将 `moduleA` 模块中的 `increment` 和 `decrement` 方法映射到组件中,最后将这些方法作为返回值返回给组件。
在组件中,我们可以直接调用 `increment` 和 `decrement` 方法,如下所示:
```javascript
increment()
decrement()
```
需要注意的是,在组合式 API 中,我们不能像在 Vue2 和 Vue3 中一样,使用 `this` 来调用方法,而是直接调用方法即可。另外,在使用组合式 API 时,我们需要使用 `useStore` 函数来获取 store 实例,而不是直接从 `this.$store` 中获取。