vuex使用简易版

这里分享vuex的2种使用场景

场景1:vuex管理数据简单只有两三个状态需要被管理

使用方案

main.js

import Vue from 'vue';
Vue.use(Vuex);
const store=new Vuex.Store({
    state:{                                  //定义初始值,也就是需要被vuex管理的值
        nickName:'admin',
        cartCount:0
    },
    mutations:{                               //定义改变vuex中值得方法
        updateUserInfo(state,nickName){
            state.nickName=nickName
        },
        updateCartCount(state,cartCount){
            state.cartCount+=Number(cartCount)
        },
        initCartCount(state,cartCount){
            state.cartCount=cartCount
        }
    }
});

new Vue({
    el: '#app',
    router,
    store,  //注册到vue实例中
    template: '<App/>',
    components: { App }
});

vue组件中使用

this.$store.commit('updateCartCount',cartCount)  //更新vuex中的cartCount,也就是需要更新vuex中的数据的时候调mutations中的方法并且传入新值用this.$store.commit('mutations中的方法名',新值)
computed:{
  nickName(){
    return this.$store.state.nickName
  },
  cartCount(){
    return this.$store.state.cartCount
  }
},                                            //需要获取vuex中的变量,并且挂载到dom上的时候,直接用计算属性,实时计算用this.$store.state.需要使用的变量

完整版查看https://blog.csdn.net/github_39274378/article/details/81542610

猜你喜欢

转载自blog.csdn.net/github_39274378/article/details/81542554