vuex以及它的5个辅助函数

vuex是vue的一个插件,是vue的状态管理库,

既然是vue的插件,那么就需要注册:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

除了注册,还需要给我们的vue的store赋值:

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //
  },

  mutations: {
//
  },
  actions: {
//
  }
})


import Vue from 'vue'
import App from './App.vue'
import store from './store'

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')


//render: function (createElement) {
    return createElement(App);
}

vuex改变数据的流程:

this.$store.dispatch触发action中定义的函数,action中的函数(可以是异步代码)commit(提交)mutation中的函数,从而改变数据,mutation是改变数据的唯一方式(且只能是同步代码)

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    todos: [{id: 0, value: "vuejs开发"}]//存储数据;
  },
  getters: {//计算属性
    counts(state){
      return state.todos.length
    }
  },
  mutations: {
    onAddTodo(state, item){
      state.todos.push(item)
    },
    onDelTodo(state, id){
      state.todos = state.todos.filter(item => item.id !== id)
    }
  },
  actions: {//action提交commit触发
    onAddTodo({commit}, item) {
      commit('onAddTodo', item)
    },
    onDelTodo({commit}, id){
      commit('onDelTodo', id)
    }
  }
})

vuex的辅助函数之mapState和mapGetter的用法和原理

这俩很相似,

都是将 store 中的 state 映射到局部计算属性中。

mapState

import { mapState } from 'vuex'
export default {
  // ...
  computed: mapState({
    // 箭头函数可以让代码非常简洁
    count: state => state.count,
    // 传入字符串 'count' 等同于 `state => state.count`
    countAlias: 'count',
    // 想访问局部状态,就必须借助于一个普通函数,函数中使用 `this` 获取局部状态
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}


computed: mapState([
  // 映射 this.count 到 this.$store.state.count
  'count'
])

computed: {
  count() {
    return this.$store.state['count']
  }
}



源码分析:

可以传入数组和对象,
function normalizeMap (map) {
  return Array.isArray(map)
    ? map.map(key => ({ key, val: key }))
    : Object.keys(map).map(key => ({ key, val: map[key] }))
}

export function mapState (states) {
  const res = {}
  normalizeMap(states).forEach(({ key, val }) => {
    res[key] = function mappedState () {
      return typeof val === 'function'//如果是对象,则对应的value值可以为函数
        ? val.call(this, this.$store.state, this.$store.getters)
        : this.$store.state[val]
    }
  })
  return res
}


mapGetter

源码分析://value值不为为函数;



export function mapGetters (getters) {
  const res = {}
  normalizeMap(getters).forEach(({ key, val }) => {
    res[key] = function mappedGetter () {
      if (!(val in this.$store.getters)) {
        console.error(`[vuex] unknown getter: ${val}`)
      }
      return this.$store.getters[val]
    }
  })
  return res
}

mapActions

export function mapActions (actions) {
  const res = {}
  normalizeMap(actions).forEach(({ key, val }) => {
    res[key] = function mappedAction (...args) {
      return this.$store.dispatch.apply(this.$store, [val].concat(args))
    }
  })
  return res
}


import { mapActions } from 'vuex'
export default {
  // ...
  methods: {
    ...mapActions([
      'increment' // 映射 this.increment() 到 this.$store.dispatch('increment')
    ]),
    ...mapActions({
      add: 'increment' // 映射 this.add() to this.$store.dispatch('increment')
    })
  }
}

mapMutations
import { mapMutations } from 'vuex'
export default {
  // ...
  methods: {
    ...mapMutations([
      'increment' // 映射 this.increment() 到 this.$store.commit('increment')
    ]),
    ...mapMutations({
      add: 'increment' // 映射 this.add() 到 this.$store.commit('increment')
    })
  }
}
export function mapMutations (mutations) {
  const res = {}
  normalizeMap(mutations).forEach(({ key, val }) => {
    res[key] = function mappedMutation (...args) {
      return this.$store.commit.apply(this.$store, [val].concat(args))
    }
  })
  return res
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值