Vuex
1 、辅助函数
-
mapState
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
})
简写带空间名称的字符串
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
-
mapActions
...mapActions([ 'some/nested/module/foo', // -> this['some/nested/module/foo']() selfDefine:'some/nested/module/ bar' // -> this['some/nested/module/bar']() ])
简写带空间名称的字符串
...mapActions('some/nested/module', [ 'foo', // -> this.foo() 'bar' // -> this.bar() ])
-
mapMutations
-
createNamespacedHelpers
创建基于命名空间的组件绑定辅助函数。其返回一个包含 mapState、mapGetters、mapActions 和 mapMutations 的对象。它们都已经绑定在了给定的命名空间上。
更好的写法:
1 import { createNamespacedHelpers } from 'vuex' 2 3 const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') 4 5 export default { 6 computed: { 7 // 在 `some/nested/module` 中查找 8 ...mapState({ 9 a: state => state.a, 10 b: state => state.b 11 }) 12 }, 13 methods: { 14 // 在 `some/nested/module` 中查找 15 ...mapActions([ 16 'foo', 17 'bar' 18 ]) 19 } 20 }
action 通过
store.dispatch
方法进行分发:乍一眼看上去感觉多此一举,我们直接分发 mutation 岂不更方便?实际上并非如此,还记得 mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:
mutation 必须同步执行这个限制么?Action 就不受约束!我们可以在 action 内部执行异步操作:
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
Actions 支持同样的载荷方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
在组件中分发 Action
你在组件中使用 this.$store.dispatch('xxx')
分发 action,或者使用 mapActions
辅助函数将组件的 methods 映射为 store.dispatch
调用(需要先在根节点注入 store
):
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}
commit 和 dispatch的区别 = 一个异步操作与同步操作的区别。
当你的操作行为中含有异步操作,比如向后台发送请求获取数据,就需要使用action的dispatch去完成了。其他使用commit即可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现