1.关于Vuex
-
什么是Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。简单的来说,store中的state就相当于组件中的data,但是这个data是全局的,在state中定义了一个数据之后在任何vue组件中都能访问他,修改他,并且你的修改能够全局的实时响应。
-
为什么要使用Vuex
以下是一个表示“单向数据流”理念的极简示意:
但是,当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:
1)多个视图依赖于同一状态。
2)来自不同视图的行为需要变更同一状态。
对于问题一,传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。对于问题二,我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码。简单来说就是解决兄弟组件之间传值繁琐,多层级父子组件传值繁琐,非关系组件之间传值困难以及多个组件同时需要更改某一组件中的数据繁琐的问题。
-
什么时候使用Vuex
小型应用不适合用使用Vuex,一个简单的 store 模式 就足够了。
当要考虑把组件的共有状态抽离出来的大型应用适合使用Vuex
-
使用Vuex的时候应该注意的
每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:
-
Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
-
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
2.如何引入Vuex
1.下载 vuex:
npm install vuex --save
2.在 src 目录下新建 store 文件夹,并在 store 文件夹下新建 index.js,内容如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {}
})
export default store
3.在 main.js 中引入 store,然后在全局注册一下 store,这样一来就可以在任何组件中使用 this.$store 了,main.js 中引入的代码如下:
import router from './router'
import store from './store'
new Vue({
el: '#app',
router, // 全局注册router
store, // 全局注册store
components: { App },
template: '<App/>'
})
3.vuex的核心state/getters/mutations/actions的用法
回到 index.js 中,在 store 的 state 中定义一个 productList 数组:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
productList: [
{ name: '苹果', price: 10 },
{ name: '西瓜', price: 15 },
{ name: '草莓', price: 50 },
{ name: '车厘子', price: 100 }
]
},
getters: {},
mutations: {},
actions: {}
})
export default store
至此,我们可以用 this.$store.state.productList 在任何组件中获取到 store 中 productList 的值,但是这并不是理想的获取方式;vuex 提供了一个 getters(类似于 vue 的计算属性 computed),来监听 state 值得变化,getters 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。getters 使用方式代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
productList: [
{ name: '苹果', price: 10 },
{ name: '西瓜', price: 15 },
{ name: '草莓', price: 50 },
{ name: '车厘子', price: 100 }
]
},
getters: {
// Getter 也可以接受其他 getter 作为第二个参数
// 获取折扣价
getDiscountPrice: (state, getters) => {
let discountPrice = state.productList.map(element => {
return { name: element.name, price: element.price * 0.8 }
})
return discountPrice
}
},
mutations: {},
actions: {}
})
export default store
接下来要说的就是mutations了,更改 Vuex 的 store 中的状态的唯一方法就是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
productList: [
{ name: '苹果', price: 10 },
{ name: '西瓜', price: 15 },
{ name: '草莓', price: 50 },
{ name: '车厘子', price: 100 }
]
},
getters: {
// Getter 也可以接受其他 getter 作为第二个参数
// 获取折扣价
getDiscountPrice: (state, getters) => {
let discountPrice = state.productList.map(element => {
return { name: element.name, price: element.price * 0.8 }
})
return discountPrice
}
},
mutations: {
// payload自定义参数
increase (state, payload = { money: 1 }) {
// 增加相应的价格
state.productList.forEach(element => {
element.price += payload.money
})
},
decrease (state, payload = { money: 1 }) {
// 减少相应的价格
state.productList.forEach(element => {
element.price -= payload.money
})
}
},
actions: {}
})
export default store
这时候在组件中就可以以 this.$store.commit('decrease', { money: 5 }) 的方式进行调用,但是 mutations 里面的方法都是同步事务,每个组件调用得到的结果都是相同的,这肯定不是我们想要的,好在 vuex 官方 API 还提供了一个 actions,这个 actions 也是个对象变量,最大的作用就是里面的 action 方法可以包含任意异步操作,这里面的方法是用来异步触发 mutations 里面的方法,actions 中的回调函数的第一个参是 context,是一个与 store 实例具有相同属性和方法的对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。actions 的用法如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
productList: [
{ name: '苹果', price: 10 },
{ name: '西瓜', price: 15 },
{ name: '草莓', price: 50 },
{ name: '车厘子', price: 100 }
]
},
getters: {
// Getter 也可以接受其他 getter 作为第二个参数
// 获取折扣价
getDiscountPrice: (state, getters) => {
let discountPrice = state.productList.map(element => {
return { name: element.name, price: element.price * 0.8 }
})
return discountPrice
}
},
mutations: {
// payload自定义参数
increase (state, payload = { money: 1 }) {
// 增加相应的价格
state.productList.forEach(element => {
element.price += payload.money
})
},
decrease (state, payload = { money: 1 }) {
// 减少相应的价格
state.productList.forEach(element => {
element.price -= payload.money
})
}
},
actions: {
asyncIncrease (context, payload) {
// 模拟异步操作
setTimeout(() => {
context.commit('increase', payload) // context提交
}, 2000)
},
asyncDecrease (context, payload) {
// 模拟异步操作
setTimeout(() => {
context.commit('decrease', payload) // context提交
}, 2000)
}
}
})
export default store
这时候在组件中就可以以 this.$store.dispatch('asyncIncrease', 5) 的方式进行调用。至此就可以做到一呼百应的全局响应状态改变了!
4.相关链接
项目github地址:https://github.com/chenqim/VUE
vuex官方网址:https://vuex.vuejs.org/zh/