vuex的多模塊使用
目錄結構
|-store
|–index.js
|–modules
|–a.js
|–b.js
1、在a.js中聲明單頁所需要的數據等
const state = {
count:1
}
const mutations = {
add(state){
state.count++;
}
}
const actions = {
addAction({commit}){
commit('add')
}
}
export defult {
namespaced:true,
state,
mutations
actions
}
2、同樣聲明b.js
3、在index.js中進行導入
import Vue from 'vue';
import Vuex from 'vuex'
//導入單頁store
import a from './modules/a'
import b from './modules/b'
Vue.use(Vuex);
//導出實例
export default new Vuex.Store({
modules:{
a,
b
}
})
4、在main.js 中導入聲明的index.js中的store
import store from './store/index'
new Vue({
...
store
}).$mount('#app');
5、在a.vue中的使用
5.1利用全局變量使用數據
{{$store.state.a.count}}
5.2利用mapState
import {mapState} from 'vuex';
computed:{
...mapState('a',["count"])
},
5.3使用mutations
import {mapMutations} from 'vuex';
methods:{
...mapMutations('a',[
'add'
]),
},
5.4 使用actions
import {mapActions} from 'vuex'
methods:{
...mapMutations([ // 未使用命名空間
'add','reduce'
]),
...mapActions('a',['addAction'])
},
修改vuex中的值,做到全局傳遞
1、在module中新建c.js
const state = {
model: {
path: '',
isShow: false
}
}
const mutations = {
setModel (state, model) {
state.model = model
}
}
const actions = {
setModel ({ commit }, model) {
commit('setModel', model)
}
}
在頁面文件中
import { mapActions } from 'vuex'
export default {
name: '',
data () {
return {
model: {
path: 'xx',
isShow: true
}
}
},
methods: {
...mapActions('c',['setModel'])
showModel () {
this.setModel(this.model)
}
}
}