vuex的使用

vue2(对应的vuex为3,版本不一致会出问题,会出现挂载不上去的问题):


//store.js
import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

let user = {
  namespaced: true, //一定要开始命名空间。
  state: { userid: 1234 },
  actions: {
    changeId(context,val){
      context.commit('setUserId',val)
    }  
  },
  mutations: {
    setUserId(state, val) {
      state.userid = val;
    }
  },
  getters: {
    getUserId(state){
      return state.userid
    }
  }
}

// 初始化
const store = new Vuex.Store({
  state:{
    count:0
  },

  getters:{
    getCount(state){
       return state.count
    }
  }

  mutations:{
    increment (state, value) {
      state.count = state.count + value
    },
    decrement (state, value) {
      state.count = state.count - value
    }
  }

  actions:{ //一般用于异步操作
    async queryData (context, value) {
        // 调用接口获取数据
        const res = await axios.get(...,value)
        //最后还是调用mutations的方法
        context.commit('increment', res.data.count)
    }
  }

  modules:{
    user
  }
})
  
export default store

//main.js
import store from '@/store'
new Vue({
  // 把store对象挂载到vue实例对象中
  store,
  render: h => h(App),
}).$mount('#app')

使用:


//获取state参数,写在computed中
import {mapState} from 'vuex'

computed: {
  //写法一:
  count () {
    return this.$store.state.count
  }
  //写法二:
  ...mapState(['count','user']),
}

//获取getters,写在computed中
import {mapGetters} from 'vuex'

//写法一
methods:{
  getCount() {
    return this.$store.getters.getCount
  },
  getUserId() {
    return this.$store.getters['user/getUserId']//获取不同模块
  }
}
//写法二:
computed: {
  ...mapGetters(['count']),
  ...mapGetters('user',[getUserId]),//获取不同模块
}

//获取mutations,写在methods中
import {mapMutations} from 'vuex'

methods:{
//写法一:
  ...mapMutations(['increment']),
  ...mapMutations('user',['setUserId']),//获取不同模块
//写法2
  getCount() {
    return this.$store.commit('increment',1)},
  }
  getUserId() {
    return this.$store.commit['user/setUserId','洒水']//获取不同模块
  }
}

//获取actions,写在methods中
import {mapActions} from 'vuex'

methods:{
//写法一:
  ...mapActions(["queryData"]),
  ...mapActions('user',['changeId']),//获取不同模块
//写法2
  query() {
    this.$store.dispatch('queryData',999)
  },
  changeId() {
    this.$store.dispatch('changeId','改名')
  },
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Goat恶霸詹姆斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值