转自
https://yeaseonzhang.github.io/2017/03/16/Vuex-%E9%80%9A%E4%BF%97%E7%89%88/
https://juejin.im/post/5b323cd36fb9a00e6b3ca3bf
https://juejin.im/entry/59191b6b0ce4630069f6a3ad#5
https://www.w3cplus.com/vue/vuex.html
Vuex是什么?
Vuex 类似 Redux 的状态管理器,用来管理Vue的所有组件状态。
为什么使用Vuex?
当你打算开发大型单页应用(SPA),会出现多个视图组件依赖同一个状态,来自不同视图的行为需要变更同一个状态。
遇到以上情况时候,你就应该考虑使用Vuex了,它能把组件的共享状态抽取出来,当做一个全局单例模式进行管理。这样不管你在何处改变状态,都会通知使用该状态的组件做出相应修改。
下面讲解如何使用Vuex。
最简单的Vuex示例
本文就不涉及如何安装Vuex,直接通过代码讲解。
import Vue from 'vue';
import Vuex form 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
需要注意的是只能通过mutations改变store的state的状态,不能通过store.state.count = 5;直接更改(其实可以更改,不建议这么做,不通过mutations改变state,状态不会被同步)。以上就是一个最简单的Vuex,每一个Vuex应用就是一个store,在store中包含组件中的共享状态state和改变状态的方法(暂且称作方法)mutations。
使用store.commit方法触发mutations改变state:
store.commit('increment');
console.log(store.state.count) // 1
一个简简单单的Vuex应用就实现了。
在Vue组件使用Vuex
如果希望Vuex状态更新,相应的Vue组件也得到更新,最简单的方法就是在Vue的computed(计算属性)获取state
// Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count;
}
}
}
上面的例子是直接操作全局状态store.state.count,那么每个使用该Vuex的组件都要引入。为了解决这个,Vuex通过store选项,提供了一种机制将状态从根组件注入到每一个子组件中。
// 根组件
import Vue from 'vue';
import Vuex form 'vuex';
Vue.use(Vuex);
const app = new Vue({
el: '#app',
store,
components: {
Counter
},
template: `
<div class="app">
<counter></counter>
</div>
`
})
通过这种注入机制,就能在子组件Counter通过this.$store访问:
// Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState函数
computed: {
count () {
return this.$store.state.count
}
}
这样通过count计算属性获取同名state.count属性,是不是显得太重复了,我们可以使用mapState函数简化这个过程。
import { mapState } from 'vuex';
export default {
computed: mapState ({
count: state => state.count,
countAlias: 'count', // 别名 `count` 等价于 state => state.count
})
}
还有更简单的使用方法:
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
Getters对象
如果我们需要对state对象进行做处理计算,如下:
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果多个组件都要进行这样的处理,那么就要在多个组件中复制该函数。这样是很没有效率的事情,当这个处理过程更改了,还有在多个组件中进行同样的更改,这就更加不易于维护。
Vuex中getters对象,可以方便我们在store中做集中的处理。Getters接受state作为第一个参数:
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)
}
}
})
在Vue中通过store.getters对象调用。
computed: {
doneTodos () {
return this.$store.getters.doneTodos
}
}
Getter也可以接受其他getters作为第二个参数:
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
mapGetters辅助函数
与mapState类似,都能达到简化代码的效果。mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
上面也可以写作:
computed: mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
所以在Vue的computed计算属性中会存在两种辅助函数:
import { mapState, mapGetters } form 'vuex';
export default {
// ...
computed: {
mapState({ ... }),
mapGetter({ ... })
}
}
Mutations
之前也说过了,更改Vuex的store中的状态的唯一方法就是mutations。
每一个mutation都有一个事件类型type和一个回调函数handler。
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
调用mutation,需要通过store.commit方法调用mutation type:
store.commit('increment')
Payload 提交载荷
也可以向store.commit传入第二参数,也就是mutation的payload:
mutaion: {
increment (state, n) {
state.count += n;
}
}
store.commit('increment', 10);
单单传入一个n,可能并不能满足我们的业务需要,这时候我们可以选择传入一个payload对象:
mutation: {
increment (state, payload) {
state.totalPrice += payload.price + payload.count;
}
}
store.commit({
type: 'increment',
price: 10,
count: 8
})
mapMutations函数
不例外,mutations也有映射函数mapMutations,帮助我们简化代码,使用mapMutations辅助函数将组件中的methods映射为store.commit调用。
注 Mutations必须是同步函数。
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment' // 映射 this.increment() 为 this.$store.commit('increment')
]),
...mapMutations({
add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
})
}
}
如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了。
Aciton
Vuex中的Action和Mutation类似,他们之处在于:1、Action 提交的是 mutation,而不是直接变更状态。2、Action 可以包含任意异步操作。
Action允许异步更新状态,但是需要使用一个已经存在的mutation。如果你需要以特定的顺序同时执行不同的mutations会非常有用。如果你以前没有接触过,也许很难理解为什么会使用异步状态的变化,所以先看看理论上它会发生什么,然后再开始下一部分。假如你运行Tumblr。如果页面中有大量长时间运行的gif图片。你只想每次载入其中一部分,比如当用户将页面滚动到底部200px时,加载20个图片。你需要使用mutation展示后面的20个。但是现在还没有后面的20个,你不知道何时到达页面底部。因此,在程序中,创建一个事件来监听滚动的位置然后触发相应的操作。然后,该操作将从数据库中检索后面20个图像的URL,并将20个图片的状态添加到mutation中然后显示。本质上,Actions创建一个请求数据的框架。它们使用一致的方法来应用异步方式中的数据。
// store.js
export const store = new Vuex.Store({
state: { counter: 0 }, // 展示内容, 无法改变状态
getters: {
tripleCounter: state => {
return state.counter * 3;
}
}, // 改变状态
//mutations 永远是同步的
mutations: {
// 显示传递的载荷 payload, 用 num 表示
increment: (state, num) => {
state.counter += num;
}
}, // 提交 mutation, 这是异步的
actions: {
// 显示传递的载荷 payload, 用 asynchNum ( 一个对象 )表示
asyncDecrement: ({ commit }, asyncNum) => {
setTimeout(() => {
// asyncNum 对象可以是静态值
commit("decrement", asyncNum.by);
}, asyncNum.duration);
}
}
});
1034

被折叠的 条评论
为什么被折叠?



