vuex 是什么?
-
vuex是一个专为vue.js 应用程序开发的状态管理模式。它采用集中式存储和管理程序的所有组件的数据
-
vuex核心?
state 所有数据都存储在state中 state是一个对象
actions 只能调用mutations的方法 是一个异步方法
mutations可以直接操作state中的数据
getters 类似于计算属性可以对state中的数据做一些逻辑操作
modules 将仓库分模块存储
-
vuex 运行机制图
-
-
代码演示
获取到state中的数据有两种方法 这两种都能获取变量
1`. 使用映射的方法
import { mapGetters } from 'vuex' //引入mapGetters
在computed 用…获取变量
computed: {
...mapGetters(["count"])
},
2 . 直接在差值表达式里写
<button>+</button>
<!-- {{count}} -->
<p>{{$store.state.count}}</p>
<button>-</button>
4 . 改变count的值代码演示
如果是同步操作 直接在mutations修改
第一步添加点击事件
<button @click="addup">+</button>
<!-- {{count}} -->
<p>{{$store.state.count}}</p>
<button>-</button>
第二步通过commit把事件名参数传过去
methods: {
addup(){
this.$store.commit("addup",1) // 第一个参数是事件 第二个参数是要加的数量
}
},
第三步在mutations中修改数据
mutations: {
addup(state, num) {
state.count += num
}
},
如果是异步操作就要通过dispatch 在actions中通过commit 在mutations中修改数据
第一步
<div>
<button @click="addup">+</button>
<!-- {{count}} -->
<p>{{$store.state.count}}</p>
<button @click="reduce">-</button>
</div>
第二步
```javascript
methods: {
reduce(){
this.$store.dispatch('reduce', 1)
}
},
第三步
actions: {
reduce({ commit }, num) {
commit('reduce',num)
}
},
第四步
mutations: {
reduce(state, num) {
setTimeout(()=>{
state.count -= num
},4000)
}
},