VUEX总共分为五个模块:
1.state:定义初始化变量,
2.mutations:更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,命名规则:动词_名词,全部大写,例如:SET_USER
3.actions: Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。命名规则:动词名词,驼峰规则 例如:setUser;
4.getters:简单来说就是对state里面的属性进行计算,所有需要访问vuex中的属性,都需使用getter来获取, getter需要单独成一个文件
state
state:{
userViews:[],
}
mutations
ADD_USERID(state,name){
if (state.userViews.some(v => v.name=== name.fullName)) return
state.userViews.push(name)
}
actions
addUserid({commit},name){
return new Promise((resolve,reject)=>{
commit ('ADD_USERID',name)
resolve("success")
})
}
getters.js
let getters = {
userViews: state => state.app(*state.action等所在的文件夹名称*).userViews,
}
export default getters
在页面中引用各个模块
state
第一种方式:
<h3>当前最新的count是:{{this.$store.state.count}}</h3>
}
第二种方式:对象展开运算符
import { mapState } from 'vuex'
computed:{
...mapState(['subCount']),
},
页面中:
<h3>当前最新的subCount是:{{subCount}}</h3>
mutations
第一种方式:
import { mapMutations } from 'vuex'
methods:{
...mapMutations(['sub','subN']),
}
页面:
<button @click="sub">-1</button>
<button @click="subN(3)">-N</button>
第二种方式:组件中使用 this.$store.commit('xxx')
<button @click="handelAdd">+1</button>
<button @click="handelAdd1">+N</button>
methods:{
handelAdd(){
this.$store.commit('add')
},
handelAdd1(){
this.$store.commit('addN',3)
},
}
actions
第一种方式:
import { mapActions } from 'vuex'
methods:{
...mapActions(['subAsyns','subNAsyns']),
}
页面:
<button @click="subAsyns">-1 Asyns</button>
<button @click="subNAsyns(3)">-N Asyns</button>
第二种方式:
<button @click="handelAdd2">+1 Async</button>
<button @click="handelAdd3">+N Async</button>
methods:{
handelAdd2(){
// dispatch来触发actions里面某个函数
this.$store.dispatch('addAsync')
},
handelAdd3(){
this.$store.dispatch('addNAsync',3)
}
}
getters
第一种方式:
import {mapGetters } from 'vuex'
computed:{
...mapGetters(['show2Num'])
},
页面:
<h1>{{show2Num}}</h1>