1、原因
因?yàn)閟tore里的數(shù)據(jù)是保存在運(yùn)行內(nèi)存中的,當(dāng)頁面刷新時(shí),頁面會(huì)重新加載vue實(shí)例,store里面的數(shù)據(jù)就會(huì)被重新賦值。
2、解決方案
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 默認(rèn)
const state = {
name: localStorage.getItem("name"), //基本消息--姓名
}
// 事件
const mutations = {
name(state, str) {//姓名
localStorage.setItem("name", str);
state.name = str;
},
}
// 在加減之前 先加10
const getters = {}
// 異步
const actions = {
setName(context,str){
context.commit("name", str);
}
}
export default new Vuex.Store({
state,
mutations,
actions
})
- 調(diào)用store
import store from '@store/index.js'
export default {
store,
mounted(){
this.$store.dispatch('setName','張三')
}
}
-
b.vue獲取
import store from '@store/index.js'
export default {
store,
mounted(){
console.log(this.$store.state)
console.log(this.$store.state.name)
}
}