1.Vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
2.什么情况下我应该使用 Vuex?
虽然 Vuex 可以帮助我们管理共享状态,但也附带了更多的概念和框架。这需要对短期和长期效益进行权衡。
如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。一个简单的 store 模式就足够您所需了。但是,如果您需要构建一个中大型单页应用,您很可能会考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择。
3.如何引入Vuex?
1.下载
vuex: npm install vuex --save
2.引入
//在main.js中引入
import Vuex from 'vuex'
Vue.use( Vuex );
const store = new Vuex.Store({
//待添加
})
new Vue({
el: '#app',
store,
render: h => h(App)
})
4. Vuex的核心概念?
在介绍Vuex的核心概念之前, 我使用vue-cli
初始化了一个demo, 准备以代码的形式来说明Vuex的核心概念, 大家可以在github上的master进行下载.这个demo分别有两个组件ProductListOne.vue
和ProductListTwo.vue
, 在App.vue
的datat
中保存着共有的商品列表, 代码和初始化的效果如下图所示:
//App.vue中的初始化代码
<template>
<div id="app">
<product-list-one v-bind:products="products"></product-list-one>
<product-list-two v-bind:products="products"></product-list-two>
</div>
</template>
<script>
import ProductListOne from './components/ProductListOne.vue'
import ProductListTwo from './components/ProductListTwo.vue'
export default {
name: 'app',
components: {
'product-list-one': ProductListOne,
'product-list-two': ProductListTwo
},
data () {
return {
products: [
{name: '糖醋里脊', price: 20},
{name: '水煮肉片', price: 40},
{name: '大盘鸡', price: 60},
{name: '干锅牛蛙', price: 80}
]
}
}
}
</script>
<style>
body{
font-family: Ubuntu;
color: #555;
}
</style>
//ProductListOne.vue
<template>
<div id="product-list-one">
<h2>Product List One</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['products'],
data () {
return {
}
}
}
</script>
<style scoped>
#product-list-one{
background: #FFF8B1;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-one ul{
padding: 0;
}
#product-list-one li{
display: inline-block;
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #E8800C;
}
</style>
//ProductListTwo.vue
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['products'],
data () {
return {
}
}
}
</script>
<style scoped>
#product-list-two{
background: #D1E4FF;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-two ul{
padding: 0;
list-style-type: none;
}
#product-list-two li{
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #860CE8;
display: block;
}
</style>
4.1 state
state
就是Vuex中的公共的状态, 我是将state
看作是所有组件的data
, 用于保存所有组件的公共数据.
我们就可以把App.vue
中的两个组件共同使用的data抽离出来, 放到state
中,代码如下:
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
products: [
{name: '糖醋里脊', price: 20},
{name: '水煮肉片', price: 40},
{name: '大盘鸡', price: 60},
{name: '干锅牛蛙', price: 80}
]
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
此时,ProductListOne.vue和ProductListTwo.vue也需要做相应的更改
<!--ProductListOne.vue-->
<template>
<div id="product-list-one">
<h2>Product List One</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
products : this.$store.state.products //获取store中state的数据
}
}
}
</script>
<style scoped>
#product-list-one{
background: #FFF8B1;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-one ul{
padding: 0;
}
#product-list-one li{
display: inline-block;
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #E8800C;
}
</style>
<!--ProductListTwo.vue-->
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
products : this.$store.state.products //获取store中state的数据
}
}
}
</script>
<style scoped>
#product-list-two{
background: #D1E4FF;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-two ul{
padding: 0;
list-style-type: none;
}
#product-list-two li{
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: rgba(255,255,255,0.7);
}
.price{
font-weight: bold;
color: #860CE8;
display: block;
}
</style>
可以看到, 将公共数据抽离出来后, 页面没有发生变化.
以上demo的代码在分支code01
4.2 Getters
vuex的官方文档也是说到可以将getter理解为store的计算属性, getters的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
我们可以在main.js中添加一个getters属性, 其中的saleProducts对象将state中的价格减少一半(除以2)
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
products: [
{name: '糖醋里脊', price: 20},
{name: '水煮肉片', price: 40},
{name: '大盘鸡', price: 60},
{name: '干锅牛蛙', price: 80}
]
},
getters:{ //添加getters
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
将productListOne.vue中的products的值更换为this.$store.getters.saleProducts
data () {
return {
products : this.$store.getters.saleProducts //获取store中state的数据
}
}
页面中,Product List One中的每项商品的价格都减少了一半
以上demo的代码在分支code02
4.3 Mutations
我将mutaions
理解为store
中的methods
, mutations
对象中保存着更改数据的回调函数,该函数名官方规定叫type
, 第一个参数是state
, 第二参数是payload
, 也就是自定义的参数.
我们在main.js
中添加mutations
属性,其中minusPrice
这个回调函数用于将商品的价格减少payload
这么多, 代码如下:
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
products: [
{name: '糖醋里脊', price: 20},
{name: '水煮肉片', price: 40},
{name: '大盘鸡', price: 60},
{name: '干锅牛蛙', price: 80}
]
},
getters:{ //添加getters
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
},
mutations:{ //添加mutations
minusPrice (state, payload ) {
let newPrice = state.products.forEach( product => {
product.price -= payload
})
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
在ProductListTwo.vue中注册minusPrice方法, 在该方法中commitmutations中的minusPrice这个回调函数 注意:调用mutaions中回调函数, 只能使用store.commit(type, payload)
<script>
export default {
data () {
return {
products : this.$store.state.products //获取store中state的数据
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2); //提交`minusPrice,payload为2
}
}
}
</script>
点击按钮后可以发现, Product List Two中的价格减少了2,(一直点,一直减)
(Product List One中的价格没有发生变化,原因是getter 监听的是map方法产生的新对象)
以上demo的代码在分支code03
4.4 Actions
actions 类似于 mutations,不同在于:
actions提交的是mutations而不是直接变更状态
actions中可以包含异步操作, mutations中绝对不允许出现异步
actions中的回调函数的第一个参数是context, 是一个与store实例具有相同属性和方法的对象
此时,我们在store中添加actions属性, 其中minusPriceAsync采用setTimeout来模拟异步操作,延迟2s执行 该方法用于异步改变我们刚才在mutaions中定义的minusPrice
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
products: [
{name: '糖醋里脊', price: 20},
{name: '水煮肉片', price: 40},
{name: '大盘鸡', price: 60},
{name: '干锅牛蛙', price: 80}
]
},
getters:{ //添加getters
saleProducts: (state) => {
let saleProducts = state.products.map( product => {
return {
name: product.name,
price: product.price / 2
}
})
return saleProducts;
}
},
mutations:{ //添加mutations
minusPrice (state, payload ) {
let newPrice = state.products.forEach( product => {
product.price -= payload
})
}
},
actions:{ //添加actions
minusPriceAsync( context, payload ) {
setTimeout( () => {
context.commit( 'minusPrice', payload ); //context提交
}, 2000)
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
在ProductListTwo.vue中添加一个按钮,为其添加一个点击事件, 给点击事件触发minusPriceAsync方法
在ProductListTwo.vue中注册minusPriceAsync方法, 在该方法中dispatchactions中的minusPriceAsync这个回调函数
<!--ProductListTwo.vue-->
<template>
<div id="product-list-two">
<h2>Product List Two</h2>
<ul>
<li v-for="product in products">
<span class="name">{{ product.name }}</span>
<span class="price">${{ product.price }}</span>
</li>
<button @click="minusPrice">减少价格</button> //添加按钮
<button @click="minusPriceAsync">异步减少价格</button> //添加按钮
</ul>
</div>
</template>
<script>
export default {
data () {
return {
products : this.$store.state.products //获取store中state的数据
}
},
methods: {
minusPrice() {
this.$store.commit('minusPrice', 2); //提交`minusPrice,payload为2
},
minusPriceAsync() {
this.$store.dispatch('minusPriceAsync', 5); //分发actions中的minusPriceAsync这个异步函数
}
}
}
</script>
<style scoped>
#product-list-two{
background: #F5FF0B;
box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
margin-bottom: 30px;
padding: 10px 20px;
}
#product-list-two ul{
padding: 0;
list-style-type: none;
}
#product-list-two li{
margin-right: 10px;
margin-top: 10px;
padding: 20px;
background: #FCDD1D;
}
.price{
font-weight: bold;
color: #E82743;
display: block;
}
</style>
点击按钮后 可以发现, Product List Two中的价格延迟2s后减少了5
以上demo的代码在分支code04
4.5 Modules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态