三十七、Vuex
一、Vuex是一个专门为Vue.js应用程序开发的状态管理模式
- 它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
- Vuex 也集成到Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
- 状态管理:可以简单的将其看成把需要多个组件共享的变量全部存储在一个对象里面;然后将对象放在顶层的vue实例中,让其他组件可以使用。(Vuex就是为了提供一个在多个组件间共享状态的插件)
二、Vuex状态管理图例
三、实例
App.vue文件
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 29 30 31 32 33 34 35 36 37 | <template> <div id= "app" > <h5>----------App内容----------</h5> <h2>{{message}}</h2> <h2>{{$store.state.counter}}</h2> <button @click= "add" >+</button> <button @click= "sub" >-</button> <h5>----------HelloVuex内容----------</h5> <!-- <hello-vuex :counter= "counter" ></hello-vuex> --> <hello-vuex/> </div> </template> <script> import HelloVuex from './components/HelloVuex.vue' export default { name: 'App' , data() { return { message: "我是App组件" , } }, components: { HelloVuex }, methods: { add(){ this .$store.commit( 'increment' ) }, sub(){ this .$store.commit( 'deincrement' ) } } } </script> |
HelloVuex.vue文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <template> <div> <h2>{{$store.state.counter}}</h2> </div> </template> <script> export default { name: 'HelloVuex' , } </script> <style> </style> |
store中的index.js文件,用于配置Vuex的相关信息
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 29 30 31 32 33 | import Vue from 'vue' import Vuex from 'vuex' //1.安装插件 Vue.use(Vuex) //2.创建对象 const store = new Vuex.Store({ state:{ counter: 1000 }, mutations:{ //方法 increment(state){ state.counter++ }, deincrement(state){ state.counter-- } }, actions:{ }, getters:{ }, modules:{ } }) //3.导出store对象 export default store |
四、Vuex核心概念
- State 保存共享状态的位置
- Getters 类似于组件中的计算属性
- Mutation 修改状态信息
- Action 做异步操作,之后再通过Mutation修改状态信息
- Module 划分模块,针对于不同模块进行数据的保存
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构