1:异步操作 全部写在actions中 actions只能调用mutations中的方法 不能直接修改 例子
actions: {//定义数据的异步方法
asyncAddNum(context,n){
//模拟异步
setTimeout(()=>{
context.commit("addNum",n);
},5000);
}
},
2:异步方法的调用
方法一 使用dispatch调用
asyncAdd(){
this.$store.dispatch("asyncAddNum",8);
}
方法二 使用辅助函数
...mapActions(["asyncAddNum"]),
asyncReduce() {
this.asyncAddNum(-1);
},
3:getters 就是computed 计算属性 生成一个新的值
state: {//表示全局的数据
num:10,
navFlag:true,
price:100
},
getters:{//计算属性
total(state){
return state.num*state.price
}
},
4:计算属性的使用
总价为{{ total }}
import { mapGetters } from "vuex";
export default {
computed: {
...mapGetters(["total"]),
5:modules 用来拆分state的 如果state的数据过多 可以分一个个的模块
Vue.use(Vuex)
声明了一个对象模块
var goodsinfo = {
namespaced:true,//支持命名
state:{
list:[1,2,3,4]
},
mutations:{
add(state,item){
state.list = [...state.list,item]
}
}
}
模块注册
modules: {
goodsinfo
}
6:模块中数据显示
页面
{{ list }}
方法一
computed: {
list(){
console.log(this.$store.state);
return this.$store.state.goodsinfo.list;
}
},
方法二
computed: {
...mapState({
list: (state) => state.goodsinfo.list,
}),
},
7:调用模块中的方法
页面
<button @click="addGoodsinfo">往模块中新增一个数</button>
事件
addGoodsinfo(){
this.$store.commit("goodsinfo/add",10);
}