Vue的学习(16)vuex

新年快乐呦

vuex 是什么:对 vue 应用中多个组件的共享状态进行集中式的管理
在这里插入图片描述我理解的流程是:从vue组件通过dispatch触发actions中对应的函数,对应的回调函数通过执行commit()来触发 mutation 的调用, 间接更新 state,state就像data中的数据,直接更新视图的显示。

demo小练习

基本的vuex使用,实现计数器的功能:
在这里插入图片描述
在这里插入图片描述

创建一个store.js 把基本的套路写好

//store
/*
vuex的核心管理对象:store
 */
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//状态对象
const state = {//初始化状态
  count:0,
}
//包含多个更新state函数的对象
const mutations = {
  //增加的mutation
  INCREMENT(state) {//这里可以理解成接收state
    state.count++
  },
  //减少的mutation
  DECREMENT(state) {
    state.count--
  }
}
//包含多个对应事件回调的对象
const actions = {
  //增加的action
  increment({commit}) {
    //提交增加的mutation
    commit('INCREMENT')//同前面一样,都是对应的关系,理解好
  },
  //减少的action
  decrement({commit}) {
    //提交减少的mutation
    commit('DECREMENT')
  },
  //带条件的action
  incrementIfOdd({commit, state}){
    if (state.count%2===1 || state.count%2===-1){
      commit('INCREMENT')
    }
  },
  //异步的action
  incrementAsync({commit}){//在action中可以直接执行异步代码
    setTimeout(() => {
      commit('INCREMENT')
    },1000)
  }
}
//包含多个getter计算属性的对象
const getters = {
  evenOrOdd(state){//这里可以理解成接收state
    return state.count%2 == 0 ? '偶数' : '奇数'
  }
}
export default new Vuex.Store({//
  state,//状态对象
  mutations,//包含多个更新state函数的对象,
  actions,//包含多个对应事件回调的对象
  getters//包含多个getter计算属性的对象
})

映射store

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


new Vue({
  el:'#app',//需要挂载到哪
  components:{App},//将App映射为标签
  template:'<App/>',//模板
  store //所有的组件对象都多了一个属性$store
})

这里的传值方式:

  1. 所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象
  2. 属性:
    state: 注册的 state 对象
    getters: 注册的 getters 对象
  3. 方法:
    dispatch(actionName, data): 分发调用 action
//App
<template>
  <div>
    <p>click {{$store.state.count}} times, count is {{evenOrOdd}}</p>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementIfOdd">increment if odd</button>
    <button @click="incrementAsync">increment async</button>
  </div>
</template>

<script>
  export default {
    computed:{
     evenOrOdd(){
       return this.$store.getters.evenOrOdd
     }
    },
    // 所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象
    methods:{
      increment(){
        //通知vuex去增加
        this.$store.dispatch('increment')//触发store中action调用
      },
      decrement(){
        this.$store.dispatch('decrement')
      },
      incrementIfOdd(){
        this.$store.dispatch('incrementIfOdd')
      },
      incrementAsync(){
        this.$store.dispatch('incrementAsync')
      },
    },
  }
</script>

<style>

</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值