vuex学习笔记

1.安装

  npm install vuex --save

2.引入

  在src中新建文件夹--命名为store,在文件中建立store.js,引入vuex

  import Vue from 'vue';

  import Vuex from 'vuex';

  Vue.use(Vuex);

  export default new Vuex.Store({

    state,

    mutations

  }) 

3.核心

  state:状态的存储;

  mapState:当组件需要获取多个状态时,可以用mapState映射store.state

    ...mapState({

      count:state=>state.count

    })

  mutations:vuex状态的唯一提交方法,-----必须是同步;mutations的触发方式是commit(type,payload);payload:最好是对象,type是方法名称;

  遵循的规则:

  a.在运用之前就初始化好需要的属性;

  b.用新对象替换老对象。es6新属性:对象展开运算符:eg:state.obj={...state.obj}

  c.使用常量替代mutations的事件类型,

    新建一个文件命名为:mutation-types.js------export const SOME_MUTATION = 'SOME_MUTATION';

    在store.js中引用,import {SOME_MUTATION} from './mutation-types'

      const store = new Vuex.Store({

        state:{...},

        mutations:{

          [SOME_MUTATAION](state){...}

        }

      })

  ...mapMutations({

    add:方法

  })

  Actions:提交的mutation,而不是直接改变状态,actions可以包含任意异步操作。

  const store = new Vuex.Store({

    state: { count: 0 },

    mutations: {

      increment (state) {

         state.count++

      }

     },

     actions: {

      increment (context) {   

        context.commit('increment') }

    }

  })

  mapActions辅助函数,将methods映射为store.dispatch调用,eg:

    import { mapActions } from 'vuex'

    export default {

      // ...

      methods: {

         ...mapActions([

           'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')

        ]),

         ...mapActions({

          add: 'increment' // 映射 this.add() 为 this.$store.dispatch('increment')

        })

      }

     }

  modules:模块化

转载于:https://www.cnblogs.com/huangmin1992/p/7195797.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值