vuex中mapState、mapGetters、mapActions、mapMutations的使用

第一步:创建store文件,添加index.js文件

第二步:安装Vuex环境npm install vuex –save,引入以下内容

import Vue from'vue'
import Vuex from'vuex'
import axiosfrom'axios'

第三步:将Vuex作为一个插件Vue.use(Vuex)

第四步:定义一个容器

let store=new Vuex.Store({
//参数与方法写在这里
//定义状态
state:{//定义在这里的数据是公用的
  num:10,
  navs:[]
},
getters:{

},
mutations:{
  add(state,playload){
    state.num+=playload.n;
  },
  desc(state,playload){
    state.num-=playload.n
  },
  getNavs(state,playload){//改变state
    state.navs=playload.res
  }
},
actions:{
  getNavs({commit}){//异步请求  通过mock模拟数据进行后台请求
    console.log('store this')
    console.log(this)
    console.log(axios)
    axios.get('http:/easy-mock.com/new/example/1/navs')
      .then((response)=>{
        commit('getNavs',{//触发mutation
          res:response.data.data
        })
      })
      .catch((error)=>{
        console.log(error)
      })
      }
}
})

第五步:将store释放出去 export defaultstore

第六步:在main.js中引入store并使用。

import storefrom'./store'
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

第七步:在要操作的页面中引入相应的扩展对象,编辑相关操作

import {mapState,mapGetters,mapActions,mapMutations}from'vuex'
export default {
      computed:{
       ...mapState({//获取数据
          num:state=>state.num,
          navs:state=>state.navs
        }),
      },
      methods:{
        //只用mapState  通过$store.commit触发mutation
        add(){this.$store.commit('add',{n:10})},
        desc(){this.$store.commit('desc',{n:10})},
        //使用mapAction mapMutation

       ...mapMutations({
          add:'add',
        }),
        //getData:function () {this.$store.dispatch('getNavs')}

        ...mapActions({//触发异步操作
         getData:'getNavs'

        }),
      },
      created() {
        //触发一下函数使加载页面时载入
       this.getData()
      }
    }

转自博客:https://blog.csdn.net/Doulvme/article/details/78221873?locationNum=7&fps=1

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值