状态管理模式Vuex
Vuex
-
定义
- Vuex 是集中式存储管理应用的所有组件的状态(数据)
-
作用
- 可实现任意组件之间的通讯
-
特点
- 当不同的组件需要对同一个状态进行读写时,或者复用的状态较多
- 能够保持数据和页面是响应式的
- 便于开发和后期数据维护
安装
cnpm install --save vuex
创建 /store/index.js
文件
// 创建 /store/index.js 文件
import Vue from 'vue' //引入Vue
import Vuex from 'vuex' //引入Vuex
Vue.use(Vuex) //应用
export default new Vuex.Store({
actions:{}, //接受用户的事件
mutations:{}, //操作state中的数据
state:{}, //存放共享的数据
})
// main.js
import store from './store/index.js'
new Vue({
el:"#app",
render: h => h(App),
store:store
})
- 实现对
store
数据的count
累加和累减- 读取
store
的state
- 读取
<h1>当前的计数:{{ $store.state.count }}</h1>
- 操作
store
的state
methods: {
// 累加
add() {
this.$store.commit("ADD", this.sum); //同步操作
// this.$store.dispatch("add", this.sum); //异步操作
},
// 累减
reduce() {
this.$store.commit("REDUCE", this.sum); //同步操作
// this.$store.dispatch("reduce", this.sum); //异步操作
},
},
store
配置actions
和mutations
//接受用户的事件
actions: {
add(context, value) {
context.commit('ADD', value);
},
reduce(context, value) {
setTimeout(() => {
context.commit('REDUCE', value);
}, 1000);
},
},
//操作state中的数据
mutations: {
ADD(state, value) {
state.count += value;
},
REDUCE(state, value) {
state.count -= value;
},
},
-
注意
actions
能够提供dispatch
方法实现异步操作mutations
必须是同步函数state
只能通过mutations
配置的方法去修改
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2019-08-06 Md5工具类