Vuex状态管理

1、vue cil 4.x版本支持vuex 3版本

npm install vue@3

2、cli安装

import Vuex from "vuex"

Vue.use(Vuex);

3、分模块

let counter={
  namespaced:true,
  state:{
    count:100,
    users:[
      {id:1,name:"张三",age:18},
      {id:2,name:"李四",age:22},
      {id:3,name:"王五",age:25},
      {id:4,name:"赵六",age:26}
    ]
  },
  getters:{
    /*
      第一个参数:本地模块中的state
      第二个参数:其它getter
      第三个参数:所有模块的state
    */

     getUsers(state,getters,rootState){
       let users=state.users.filter(res=>res.age>18);
       return users
     } 
  },
  mutations:{
    inc(state,payload){
      console.log(state,payload);
      state.count+=payload.amount;
    }
  },
  actions:{
    asyncInc(conText,payload){
      setTimeout(()=>{
        console.log(conText,payload)
        conText.commit("inc",payload)
      },30)
    }
  }
}

let cart={
  namespaced:true,
  state:{
    count:0
  },
  mutations:{
    inc(state,payload){
      state.count+=payload.amount;
    }
  }
}

4、store加载模块

let store=new Vuex.Store({
  modules:{
    counter,
    cart
  }
});

5、vue引入模块

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

6、组件内部引入vuex

import {mapState,mapGetters,mapMutations,mapActions} from "vuex";

7、操作函数

    created(){
          console.log(this.$store.state.counter.count)
    },
    
    methods:{
      goShopping(url){
        window.location.href=url
      },
      handleClick(){
        this.$emit('handleClick', "我是子组件");
      },
      ...mapMutations({
        inc:"counter/inc",
        cartInc:"cart/inc"
      }),
      ...mapActions({
        asyncInc:"counter/asyncInc"
      }),
      increment(){
        // this.$store.commit("inc",{amount:10})
        // this.inc({amount:10})
        // this.$store.dispatch("asyncInc",{amount:10})
        this.asyncInc({amount:10})
      },
      cartIncrement(){
        this.cartInc({amount:1})
      }
    },

    computed:{
      ...mapState({
        count:state=>state.counter.count,
      }),
      ...mapGetters(['counter/getUsers'])
    }

8、页面导入

    <div>
        计数器{{$store.state.counter.count}},{{count}}
        <button type="button" @click="increment">+</button>
        购物车数量:{{$store.state.cart.count}}
        <button type="button" @click="cartIncrement">+</button>
      </div>
      <ul>
        <li v-for="item in getUsers" :key="item.id">
          {{item.name}}--{{item.age}}
        </li>
      </ul>
    </div>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值