Vuex学习-vuex基本使用流程

1. 向外暴露store对象

store.js

/**
 * vuex的核心管理对象模块:store
 */

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

 Vue.use(Vuex)

 //状态对象
 const state ={}

 // 包含多个直接更新 state 的方法(回调函数)的对象
 const mutations = {}

 // 包含多个事件回调函数的对象
 const actions = {}

 // 包含多个计算属性(get)的对象
 const getters = {}

export default new Vuex.Store({
  state, //状态对象
  mutations, // 包含多个直接更新 state 的方法(回调函数)的对象
  actions, // 包含多个事件回调函数的对象
  getters // 包含多个计算属性(get)的对象
})

2. 映射store

import store from './store'
	new Vue({
		store
})

3. store对象

  1. 所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象
  2. 属性:
    state: 注册的 state 对象
    getters: 注册的 getters 对象
  3. 方法:
    dispatch(actionName, data): 分发调用 action

4. 使用过程

  1. 触发函数(App.vue)
    <button @click="increment">+</button>
  1. 定义函数方法(App.vue)
methods: {
      //增加
      increment () {
        // 通知vuex去更新
        this.$store.dispatch('increment') // 分发调用 action
      }
     }
  1. dispatch action(store.js)
    定义state
const state = {
  count: 0
 }
const actions = {
  increment ({commit}) {
    // 提交增加mutation
    commit('INCREMEMT')
  }
 }
  1. commit mutation(store.js)
const mutations = {
  //增加
  INCREMEMT (state) {
    state.count++
  }
 }

5. 编码简化

首先引入
import {mapState, mapGetters, mapActions} from 'vuex'

简化后的编码

computed: {
      ...mapState(['count']), 
      ...mapGetters(['evenOrOdd']) 
    },
    methods: {
      ...mapActions([
        'increment', 
        'decrement', 
        'incrementIfOdd', 
        'incrementAsync'
        ])
    },

补充,当命名不一致时

store.js

const getters = {
  evenOrOdd2 (state) { // 不需要调用,只需要读取属性值
  return state.count%2===0 ? '偶数' : '奇数'
  }
 }

App.vue

<p>{{evenOrOdd}}</p>
<script>
  import {mapState, mapGetters, mapActions} from 'vuex'
  export default {
    computed: {
      ...mapGetters({evenOrOdd: 'evenOrOdd2'}) 
    },
  }
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值