vuex
vueX 是一个专门为 Vue.js 应用设计的状态管理架构,统一管理和维护各个vue组件的可变化状态。
state => 基本数据
getters => 从基本数据派生的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
modules => 模块化Vuex
install
cnpm install vuex --save
store.js配置
#自己创建store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
main. js配置
import store from './vuex/store' // 引入store
new Vue({
render: h => h(App),
store:store,
}).$mount('#app')
state
#state即Vuex中的基本数据! (store.js)
const store = {
state: {
count:0
}
}
export default new Vuex.Store({
state,
})
#vue 组件
<template>
<div id="app">
<el-container>
<el-header>{{$store.state.count}}</el-header>
</el-container>
</div>
</template>
mutations
const mutations = new Vuex.Store{
mutationsAddCount(state, n = 0) {
return (state.count += n)
},
mutationsReduceCount(state, n = 0) {
return (state.count -= n)
}
}
export default new Vuex.Store({
state,
mutations,
})
# components->methods
andleAddClick(n){
this.$store.commit('mutationsAddCount',n);
},
handleReduceClick(n){
this.$store.commit('mutationsReduceCount',n);
},
actions
const actions = {
actionsAddCount(context, n = 0) {
console.log(context)
return context.commit('mutationsAddCount', n)
},
actionsReduceCount({ commit }, n = 0) {
return commit('mutationsReduceCount', n)
}
}
export default new Vuex.Store({
state,
mutations,
actions,
})
# components->methods
handleActionsAdd(n){
this.$store.dispatch('actionsAddCount',n)
},
handleActionsReduce(n){
this.$store.dispatch('actionsReduceCount',n)
},
getters
#Getter会暴露为store.getters对象,可以直接以属性的形式访问这些值
export default new Vuex.Store({
//创建一个对象来保存应用启动时的初始状态
state:{
// 应用启动时, count置为0
count:0,
todos: [
{ id: 1, text: '水果类', done: true },
{ id: 2, text: '苹果', done: true },
{ id: 3, text: '苹果', done: false}
]
},
getters: {
doneTodos: state => {//通过方法访问
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {//通过属性访问
return getters.doneTodos.length
}
}
})
///属性访问
this.$store.getters.doneTodos
Getter 也可以接受其他 getter 作为第二个参数:
getters: {
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
调用:
this.$store.getters.doneTodosCount
#可以通过让getter返回一个函数,来实现给getter传参,在对 store 里的数组进行查询时非常有用。
getters: {
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
调用:
store.getters.getTodoById(2)
mapGetters 辅助函数
import { mapGetters } from 'vuex'
export default {
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
如果想将一个 getter 属性另取一个名字,使用对象形式:
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
当mapGetters([])内部是中括号时,标识填充的是字符串数组,每个字符串标识的就是一个定义在store中的getter
当mapGetters({})内部是大括号时,标识填充的是对象,是用当前实例的对象混入定义在store中的getter
实际使用参看:https://blog.youkuaiyun.com/wang839305939/article/details/73398585