vue-store模式
vueX
props
$emit
vuex使用步骤
// 引入Vue、Vuex三方件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user,
search
},
getters
})
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
vuex基本概念:
state:单一状态树
mapState:辅助函数
作用:当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。
import { mapState } from 'vuex'
export default {
// ...
computed: {
localComputed () { /* ... */ },
...mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
}
getter
作用:类似state的计算属性,用于对state进行二次加工,eg:filter
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
获取:this.$store.getters.doneTodosCount
mapGetters:辅助函数
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
// mapGetters取别名
mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
Mutation (同步提交)
作用:改变state状态值的唯一方法是提交mutation
注意:mutation 必须是同步函数
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state,payload) {
// 变更状态
state.count += payload.amount
}
}
})
// 提交方式(10,称为载荷)
store.commit('increment', {
amount:10
})
mapMutation
作用:将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
action(异步提交)
作用:异步提交mutation,并非直接修改state状态
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
dispatch(分发)
作用:异步提交action载荷
store.dispatch('incrementAsync', {
amount: 10
})
Modules
const moduleA = {
state: { count: 0 },
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
doubleCount (state) {
return state.count * 2
}
}
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
命名空间