1、原因
因為store里的數據是保存在運行內存中的,當頁面刷新時,頁面會重新加載vue實例,store里面的數據就會被重新賦值。
2、解決方案
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 默認
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
})
- 調用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)
}
}