Vuex 拾遗
引入Vuex的目的:为众多的Vue组件提供一个全局管理共享组件状态的控制中心,当一个共享状态改变时,能使调用该共享状态的组件得到更新。并且使用Vuex的API,每个共享状态的改变都能被追踪。
组件如何引入Vuex:
组件在实例化时,通过store选项引入Vuex的共享变量。之后组件通过this.$store.someprops.subprops访问共享变量
Vuex 通过 store 选项,提供了一种机制将状态从根组件『注入』到每一个子组件中(需调用 Vue.use(Vuex)): const app = new Vue({ el: '#app', // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 store, components: { Counter }, template: ` <div class="app"> <counter></counter> </div> ` })
组件的重构为使用Vuex的方式,需要作出的改变:
1、将组件从data获取数据的方式改为计算属性去处理。
1 2 3 4 5 | computed:{ shareData(){ return this .$store.state.shareData } } |
Vuex 四大关键词:state,getters,mutations, actions
state:基本的共享状态定义,组件通过this.$score.state.props访问,有简化方法mapState;
getters:适用于对state进行计算,组件通过this.$score.getters.props访问,有简化方法mapGetters;
mutations:用来改变state的状态,由state.commit('mutationtype')调用,只能用同步方法,有简化方法mapMutations;
actions:解决mutations不能用异步方法的缺陷,其提供了context参数,通过context.commit,context.dispatch触发mutations,或者通过 context.state
和 context.getters
来获取 state 和 getters,有简化方法mapActtions
备注:还有一个modules参数,支持将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // make sure to call Vue.use(Vuex) if using a module system const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment: state => state.count++, decrement: state => state.count-- } }) new Vue({ el: '#app' , computed: { count () { return store.state.count } }, methods: { increment () { store.commit( 'increment' ) }, decrement () { store.commit( 'decrement' ) } } }) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署