Vuex 四个属性
state,mutations,getters,actions(先说前面两个)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
mutations,
getters,
})
复制代码
1.state (相当于参数/对象)-辅助函数(mapState)
const state = {
count:1
}
复制代码
2.mutations(相当于方法,vue中的methods)-辅助函数(mapMutations)
const mutations = {
add(state,n){
state.count+=n;
},
reduce(state){
state.count-=1;
},
}
复制代码
3.getters(相当于计算属性,vue中的computed)-辅助函数(mapGetters)
const getters = {
count(state){
return state.count +=100;
}
}
复制代码
4.actions(和mutations差不多,mutations为同步,actions为异步)(mapActions)
- actions不能直接单独修改state里面的值,需要用到mutations来间接修改。
mutations: {
INCREMENT(state,val){
state.val = val
}
}
actions: {
incrementAsync( {commit} ){
return new Promise((resolve,reject) =>{
setTimeout(()=>{
commit('increment',val)
resolve()
},1000)
})
}
}
methods:{
add(){
this.incrementAsync({'我是值'})
},
..mapActions['incrementAsync']
}
复制代码
<template>
<div class="vuex">
<h2>{{msg}}</h2>
<hr/>
<h3>{{count}}</h3>
<div>
<button @click="add(2)">+</button>
<button @click="reduce()">-</button>
</div>
<div>
<span>改变count内的值</span>
<button @click="changeCount()">变为666</button>
</div>
</div>
</template>
<script>
import {mapState,mapMutations,mapGetters } from 'vuex';
export default{
data(){
return{
msg:'Hello Vuex',
}
},
created(){
},
methods:{
...mapMutations(['add','reduce']),
changeCount(){
console.log(32,this.count);
}
},
computed:{
...mapState(['count']),
}
}
</script>
复制代码
*注意事项
要改变state内参数的值,只能在mutations中调用方法改变。
由于页面刷新之后,数据就没了,要本地存储下
localStorage.getItem("vuex_store_second") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("vuex_store_second"))));
window.addEventListener("beforeunload",()=>{
localStorage.setItem("vuex_store_second",JSON.stringify(this.$store.state))
});
复制代码