新年快乐呦
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
})
这里的传值方式:
- 所有用 vuex 管理的组件中都多了一个属性$store, 它就是一个 store 对象
- 属性:
state: 注册的 state 对象
getters: 注册的 getters 对象 - 方法:
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>