前言
1.模塊化vuex
2.獲取vuex中的數(shù)據(jù)
3.設(shè)置vuex中的數(shù)據(jù)
4.刷新之后,保留數(shù)據(jù)
模塊化vuex
數(shù)據(jù)結(jié)構(gòu)
index.js
import Vue from "vue";
import Vuex from "vuex";
import transaction from "./modules/transaction";
Vue.use(Vuex);
export default new Vuex.Store({
plugins: [],
modules: {
transaction,
},
})
transaction.js模塊
const state = {
productCode:'',
}
// getters
const getters = {
getProductCode: state => {
return state.productCode
},
}
// actions
const actions = {
setProductCode(conText, data) {
conText.commit('setProductCode', data);
},
}
// mutations
const mutations = {
setProductCode(state, data) {
state.productCode = data
},
}
export default {
namespaced: true,//為了解決不同模塊命名沖突的問(wèn)題
state,
getters,
actions,
mutations
}
namespaced
注意:namespaced是為了解決不同模塊命名沖突的問(wèn)題,分兩種情況來(lái)寫(xiě)
1. namespaced:true
獲取vuex中的數(shù)據(jù)
<script>
import { mapState,mapGetters,mapActions } from 'vuex'
export default {
data() {
return {
productCode:'',
};
},
computed: {
...mapGetters({
'getProductCode':'transaction/getProductCode',
}),
},
watch:{
getProductCode(){
console.log(this.getProductCode)
this.productCode = this.getProductCode;
}
},
};
</script>
設(shè)置vuex中的數(shù)據(jù)
<script>
import { mapState,mapGetters,mapActions } from 'vuex'
export default {
data() {
return {
};
},
methods: {
...mapActions({
setProductCode:'transaction/setProductCode',
}),
getData() {
// this.$store.dispatch('transaction/setProductCode', 1)
this.setProductCode(1)
}
});
},
};
</script>
2. namespaced:false
如果將namespaced設(shè)置為false丽已,則需要注意命名不能重復(fù)
- 獲劝龆隆:this.$store.state.productCode
- 設(shè)置:this.$store.dispatch('productCode',‘1)
也可以使用mapState,mapGetters,mapActions
<script>
import { mapState,mapGetters,mapActions } from 'vuex'
export default {
data() {
return {
};
},
computed: {
...mapGetters(["getProductCode"]),
},
mounted(){
...mapActions(["setProductCode"]),
console.log(this.getProductCode)//獲取
this.setProductCode(1)//設(shè)置
},
};
</script>
刷新之后沛婴,保留數(shù)據(jù)
安裝
npm install vuex-persistedstate --save-dev
修改index.js配置吼畏,將數(shù)據(jù)保存到sessionStorage
import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import transaction from "./modules/transaction";
Vue.use(Vuex);
export default new Vuex.Store({
plugins: [createPersistedState({
storage: window.sessionStorage,
reducer(val) {
return {
// 需要儲(chǔ)存的數(shù)據(jù)
transaction:val.transaction,
}
}
})],
modules: {
transaction,
},
})