Vuex总结
- 全局单例模式管理 单一状态树,就是只有一个对象来存储数据SSOT
纯粹对象的概念就是,只写在{}内的,排除prototype以及原型链中的数据
大型的单页应用
vuex中的数据响应式的
只能通过commit来更改
state
访问数据: this.$store.state.count
getters
- mapGetters
对数据进行过滤
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)
}
}
})
// 访问Getters
this.$store.getters.doneTodos
// 高级用法,让getter返回函数
getters: {
getTodoById: (state) => (id) => {
// 找到todos数组中第一个匹配的
return state.todos.find(todo=>todo.id===id)
}
}
/**
* Array
* find
* indexOf
* findIndex
* some
* every
* sort
*/
mutations
改变state中的数据
const store = new Vue.Store({
state:{
count:1
},
mutations: {
increment (state) {
state.count++
}
}
})
// 使用
store.commit('increment')
提交负载:额外的参数, 大多数的情况下为一个对象
mutations: {
increment(state,n) {
state.count +=n
}
}
// 对象的提交方式
mutations: {
increment (state,payload) {
state.count += payload.amount
}
}
store.commit({
type:"increment",
amount:10
})
在组建中提交mutation
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')`
})
}
}
为什么mutation必须是同步函数
Action
处理异步而出现的,提交的是mutations
action -> mutations
action中可以包含任意操作
const store = new Vue.Store({
state: {
count:0
},
mutations: {
increment(state) {
state.count++
}
},
actions: {
// 使用参数解构,actions中的函数接受一个store实例
increment({commit}) {
commit('increment')
},
incrementAsync({commit}) {
setTimout(()=>{
commit('increment')
},1000)
}
}
})
// 最简单的分发action
store.dispatch('increment')
// 负载形式分发:就是传入参数分发
store.dispatch('incrementAsync',{amount:10})
// 对象形式分发
store.dispatch({
tyep:"incrementAsync",
amount:10
})
// 异步调用API和,分发多重的mutations
actions: {
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}