一、什么是vuex
状态管理模式
属性:
state 类似于data 存放公共数据
getters 类似于computed
mutations 类似于methods
action 提交mutations
modules 细分上面四个属性,更好管理
二、如何使用
//vuex.js
state:{
str:'aaa',
num:1
},
getters:{
changeStr(state){
return state.str+'b'
}
},
mutations:{
btn(state,c){
console.log(c) //aa
},
add(state){
state.num++
}
},
actions:{
btns({commit}){
setTimeout(()=>{
commit('add')
},1000)
}
}
//组件
<div>
{{str}}
{{changeStr}}
//mutations
<button @click="btn("aa")"></button>
//actions
<button @click="btns("aaa")"></button>
</div>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
computed:{
...mapState(['str']),
...mapGetters(['changeStr'])
},
methods:{
...mapMutations(['btn']),
...mapActions(['btns'])
}
三、vuex是单向数据流
直接修改会报错。要通过mutaions
四、vuex如何做持久化存储
vuex本身不是持久化存储
1.使用localstorage
2.使用vuex插件 npm install --save vuex-persist(原理也是使用了localstorage)