vue2中Vuex的基本使用

Vuex

vuex中一般存储组件之间共享的数据,适用于多组件共享某些数据,将这些共享的数据集中起来管理

vuex中数据都是响应式的,能够保持数据与页面的同步,数据改变重新解析模板

是实现集中式状态管理的一个Vue插件,适用于任意组件间通信

  1. 搭建vuex环境

    安装vuex

    npm i vuex安装的是vuex4版本,该版本只能用在vue3,vue2只能用vuex3版本 npm i vuex@3

    (1)创建store文件:src/store/index.js (先要有vuex,再创建store实例)

    store实例对象是由Vuex.store({})构造出来的,构造之后,在vc,vm上就会出现$store属性

    $store属性中 有dispatch,commit方法

    //引入vue
    import Vue from 'vue'
    //引入vuex
    import Vuex from 'vuex'
    Vue.use(Vuex)
    //用于响应组件中的动作
    const actions = {}
    //用于储存数据
    const state = {}
    //用于操作数据
    const mutations = {}
    //创建并导出store
    export default new Vuex.Store({
      actions, mutations, state
    })
    

    (2)在main.js中引入store

    //引入store
    import store from './store'
    //创建vm
    new Vue({
      render: h => h(App),
      store,
      beforeCreate() {
        Vue.prototype.$bus = this
      }
    }).$mount('#app')
    
  2. 基本使用

    1.在组件中使用dispatch给actions

     this.$store.dispatch("jia", this.n);
    

    2.在store中配置actions,actions主要写业务逻辑,将数据commit给mutations进行操作

    如果没有网络请求或业务逻辑,可以直接越过actions,直接编写commit

    const actions = {
      //context上下文,有commit,dispatch,state属性
      jia(context, value) {
        context.commit('JIA', value)
      },
      jian(context, value) {
        if(context.state.sum % 2){
            context.commmit('JIA',value)
        }
      }
    }
    

    3.mutations主要进行数据加工

    mutations会收到两个参数,第一个是state,第二个就是传递过来的数据

    const mutations = {
      JIA(state, value) {
        state.sum += value;
      },
      JIAN(state, value) {
        state.sum -= value;
      }
    }
    

    4.state 就是将一些共享的数据存放进来,类似与组件中的data

    在组件模板中想使用state中数据 $store.state.sum

    //用于储存数据
    const state = {
      sum: 0
    }
    

    5.getters 就是将state中的数据进行运算加工,类似与组件中的computed

    在组件中读取 $store.getters.bigData

    const getters = {
      bigData(state){
         return state.sum*10  //必须要用return语句,收到的参数就是state
      }
    }
    

    6.mapState帮助程序猿简化代码,优化computed计算属性

    首先要在组件中引入mapState import {mapState} from 'vuex'

    computed: {
        //借助mapState生成计算属性,从state中读取sum,并且形成sum函数
        ...mapState(["sum"]),//==>sum(){
                                    //return this.$store.state.sum
    		                        	}
      },
    

    7.mapActions,模板中调用的函数要传参increment(n)

    帮我们生成与actions对话的方法,即this.$store.dispatch("jia", this.n);

      methods: {
        // increment() {
        //   this.$store.dispatch("jia", this.n);
        // },
        ...mapActions({ increment: "jia" }),
      },
    

    mapActions使用时若需要传参,则要在模板绑定事件时传递参数,否则参数是事件对象

     <button @click="increment(n)">+</button>
    
    1. mapMutations,模板中调用的函数要传参increment(n)
      methods: {
        // increment() {
        //   this.$store.commit("jia", this.n);
        // },
        ...mapMutations({ increment: "jia" }),
      },
    
  3. vuex模块化

让代码更好维护,让数据分类更加明确

​ (1)修改store.js

// count相关配置
const countOptions = {
  namespaced:true,  //开启命名空间,mapState,mapActions等才能识别是哪个配置中的state,actions等
  actions:{
    addOdd(context,value){
      if(context.state.sum % 2){
        context.commit('ADDODD',value);
      }
    }
  },
  mutations:{
    ADD(state,value){
      state.sum += value;
    },
    DECREASE(state,value){
      state.sum -= value;
    },
    ADDODD(state,value){
      state.sum += value;
    }
  },
  state:{
    sum:0,
  },
  getters:{
  }
}

//person相关配置
const personOptions = {
  namespaced:true,
  actions:{
  },
  mutations:{
    ADDPERSON(state,value){
      console.log(value);
      state.personList.unshift(value)
    }
  },
  state:{
    personList:[{id:'000',name:'李四'}]
  },
  getters:{
    length(state){
      return state.personList.length
    }
  }
}
//导出时要加modules:{}
export default new Vuex.Store({
  modules:{
    countAbout:countOptions,
    personAbout:personOptions
  }
})

​ (2)组件读取数据

  • 读state中数据
//直接读取
this.$store.state.count.sum
//借助mapState
...mapState('countAbout',['sum'])
  • 组件中调用commit,dispatch,getters的方式都类似
//直接读取
this.$store.commit('countAbout/ADD',person)
//借助mapState
...mapMutations('countAbout',{add:'ADD'})

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值