vuex是什么
vuex是一个专门为vue开发的状态管理工具,它采用集中式存储管理应用的所有组件的状态,其核心是state。
vuex内容
state:存放状态数据的地方,其中数据是响应式的,数据改变对应组件的数据也会跟新改变,禁止直接改变state中的数据否则数据无法被调试工具监测。
getter:可理解为store的计算属性,能读取state中的数据。
mutations:(同步)装着处理数据逻辑方法的集合体,是该改变state中数据的唯一方法,修改数据是同步的。
actions:(异步)提交mutations修改数据,与mutations功能类似,但修改数据是异步的,可以包含任意异步操作。
const store = new Vuex.Store({
state:{
count:0;
},
mutations:{
increment(state){
state.count++
}
},
action:{
increment(context){
context.commit('increment')
}
}
})
modules:当store过于臃肿时,可使用modules将store分割成模块,每个模块中都有自己的state、getter、mutations、actions
在使用页面
放在computed里的内容有(state、getter)
放在methods里的内容有(mutation、action)
view
<p>{{getTodoById(2).text}}</p>
<button @click="asyncIncrement">点我</button>
store
mutations:{
increment(state,{num=1}){
//mutation提交会立即形成一条改变记录
state.count+=num
},
[SOME_MUTATION](state){
//专门设置mutations文件存放常量,有助于多人能够很快知道页面有哪些mutation
state.message = 'hello'
}
},
actions:{
increment({commit},{num = 1}){
setTimeout(function(){
commit({
type:'increment',
num
})
},1000)
}
},
getters:{
remaining:state=>{
return state.todos.filter(item=>item.done===false).length
},
getTodoById:state=>{
return id=>{
return state.todos.find(item=>item.id === id)
}
}
})
script的export default中
methods:{
//不建议在组件中直接修改容器中的数据,因为无法被调试工具记录到
increment(){
this.$store.commit({
type:'increment',
num:2
})
},
asyncIncrement(){
this.$store.dispatch('increment',{
num:2
})
},
...mapAction(['asyncIncrement'])
...mapMutations(['COME_MUTATION'])
computed:{
count(){
return this.$store.state.count
}
...mapState({
count:'count',
message:'message',
})
...mapGetters(['remaining','getTodoById'])
}