Vuex: 集中式的数据管理(读、写)插件,可实现任意组件间通信。
简单使用:
npm i vuex
import store from './store/index'
new Vue({
render: h => h(App),
store
}).$mount('#app')
index.js配置文件
index.js文件
import Vuex from 'vuex'
Vue.use(Vuex)
注意点:在创建store对象之前需要加载Vue.use(vuex)
actions中的context参数
commit:触发 mutations
dispatch:触发 actons
getters:根据state计算的新值并return
state:保存数据
getter配置项,对数据进行加工
state 配置项用于保存数据
const state = {
sum: 0,
school:'home',
subject:'vue'
}
getters 配置项,用于对数据进行加工
const getters = {
bigSum(state){
return state.sum * 10
}
}
...mapXxx生成方法
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
computed: {
生成计算属性方法
...mapState({ school: 'school', subject: 'subject' }),
数组写法:生成的计算属性名和读取的名称一致
...mapState(['school', 'subject']),
生成计算属性方法
...mapGetters(['bigSum'])
}
methods简写说明
页面调用:
<button @click="ADD(n)">+</button>
<button @click="SUB(n)">-</button>
<button @click="odd(n)">当前求和为奇数+</button>
<button @click="wait(n)">等一等加</button>
methods:{
简写
mapMutations 生成对应的方法,方法中会调用commit去联系mutations
...mapMutations(['ADD', 'SUB']),
mapActions 生成对应的方法, 方法中会调用dispatch去联系action
...mapActions(['odd', 'wait'])
正常写法
increment() {
this.$store.commit('ADD', this.n) // mutations
},
decrement() {
this.$store.commit('SUB', this.n)
},
odd() {
this.$store.dispatch('odd', this.n) // actions
},
wait() {
this.$store.dispatch('wait', this.n)
}
}
Vuex模块化
不同的功能会维护很多方法和数据,不同功能的方法和数据不能混在一起,所以需要对vuex中的结构进行分类管理。
将index.js中的actions、mutations、state多个功能的方法、数据进行拆分。分成一个功能一个js
将多个功能的对象,在index.js中进行创建暴露
import countOptions from './count'
import personOptions from './person'
export default new Vuex.Store({
// 两个模块的配置
modules:{
countOptions,
personOptions
}
})
结构:
store
countOptions
personOptions
使用有两种方式:
通过...mapXxx形式
computed:{
...mapState('countOptions', ['sum', 'school', 'subject']),
...mapState('personOptions', ['personList']),
...mapGetters('countOptions', ['bigSum'])
},
methods:{
// mapMutations 生成与mutations对应的方法,方法中会调用commit去联系mutations
...mapMutations('countOptions', ['ADD', 'SUB']),
// mapActions 生成与acions对应的方法, 方法中会调用dispatch去联系action
...mapActions('countOptions', ['odd', 'wait'])
}
通过方法的形式
computed: {
personList() {
return this.$store.state.personOptions.personList
},
},
methods: {
add() {
const obj = { id: nanoid(), name: this.name } // 正常的写法,namespaced需要带上
this.$store.commit("personOptions/ADD_PERSON", obj)
this.name = ''
},
addPerson() {
this.$store.dispatch('personOptions/addPersonServer')
}
}