vue - vuex的综合使用

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)
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值