vuex官方文档
1、安装
npm install vuex --save
在main.js中全局引入
import Vuex from 'vuex'
Vue.use(Vuex)
安装后会有一个store/index.js文件
2、state
由于vuex的状态存储是响应式的,那么在组件中,我们就可以用计算属性
来获取state状态
<template>
<div id="app">
<h2>product-one</h2>
<ul>
<li v-for="(item,index) in product" :key="index">
<div class="name" v-text="item.name"></div>
<div class="price" v-text="item.price"></div>
</li>
</ul>
</div>
</template>
<script>
export default {
components:{
},
data() {
return {
}
},
created(){
},
computed:{
product(){
return this.$store.state.product //获取状态机中状态
}
},
watch:{
},
methods: {
}
};
</script>
<style>
#app{
padding: 1rem;
}
ul{
list-style: none;
padding: 0;
}
</style>
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
product:[
{name:'apple', price: '2'},
{name:'banana', price: '3'},
{name:'pear', price: '4'},
{name:'melon', price: '5'}
]
},
mutations: {
},
actions: {
},
modules: {
}
})
3、state语法糖mapState
在使用的时候,computed接收mapState函数的返回值,你可以用三种方式去接收store中的值,具体可以看注释.
<template>
<div id="app">
<h2>product-one</h2>
<ul>
<li v-for="(item,index) in product" :key="index">
<div class="name" v-text="item.name"></div>
<div class="price" v-text="item.price"></div>
</li>
</ul>
<div class="count">{{count}}</div>
<div>{{message}}</div>
<div>{{myComputed}}</div>
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
components:{
},
data() {
return {
str:'中国'
}
},
created(){
},
// computed:{
// product(){
// return this.$store.state.product
// }
// },
computed:mapState({
product:'product', //第一种,通过属性访问
count:state => state.count, //第二种(可以箭头函数),通过方法访问
message(sate){ //第三种,用普通函数this指向vue实例,通过方法访问
return this.str + ' ' + this.$store.state.str
},
//测试计算属性的原本用法
//一个计算属性使用了箭头函数,则 this 不会指向这个组件的实例,具体参考vue api computed
myComputed(){
return '测试' + this.str
}
}),
watch:{
},
methods: {
}
};
</script>
<style>
#app{
padding: 1rem;
}
ul{
list-style: none;
padding: 0;
}
.count{
background: #ededed;
}
</style>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
product:[
{name:'apple', price: '2'},
{name:'banana', price: '3'},
{name:'pear', price: '4'},
{name:'melon', price: '5'}
],
count:0,
str:'江西九江'
},
mutations: {
},
actions: {
},
modules: {
}
})
4、对象展开运算符...
<template>
<div id="app">
<h2>product-one</h2>
<ul>
<li v-for="(item,index) in product" :key="index">
<div class="name" v-text="item.name"></div>
<div class="price" v-text="item.price"></div>
</li>
</ul>
<div class="count">{{product}}</div>
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
components:{
},
data() {
return {
str:'中国'
}
},
computed:{
...mapState({
product(){
return this.$store.state.product
}
})
}
};
</script>
<style>
#app{
padding: 1rem;
}
ul{
list-style: none;
padding: 0;
}
.count{
background: #ededed;
}
</style>
5、getter
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数
<template>
<div id="app">
<h2>product-two</h2>
<ul>
<li v-for="(item,index) in product" :key="index">
<div class="name">水果名:{{item.name}}</div>
<div class="price">价格{{item.price}}</div>
</li>
</ul>
</div>
</template>
<script>
export default {
components:{
},
data() {
return {
str:'中国'
}
},
computed:{
product(){
return this.$store.getters.changeProduct
}
},
};
</script>
<style>
#app{
padding: 1rem;
}
ul{
list-style: none;
padding: 0;
}
.count{
background: #ededed;
}
</style>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
product:[
{name:'apple', price: '2'},
{name:'banana', price: '3'},
{name:'pear', price: '4'},
{name:'melon', price: '5'}
],
count:0,
str:'江西九江',
},
//Getter 接受 state 作为其第一个参数
getters:{
changeProduct: (state) => {
return state.product.map(val => {
return {
name: '**' + val.name + '--',
price: val.price*2
}
})
return state.product
}
},
mutations: {
},
actions: {
},
modules: {
}
})
...mapGetters
使用方法
<ul>
<li v-for="(item,index) in changeProduct" :key="index">
<div class="name">水果名:{{item.name}}</div>
<div class="price">价格{{item.price}}</div>
</li>
</ul>
<div>{{changeProduct}}</div>
</div>
======
import {mapGetters} from 'vuex'
computed:{
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'changeProduct'
])
}
};
index.js文件同上
如果你想将一个 getter 属性另取一个名字,使用对象形式:
<li v-for="(item,index) in product" :key="index">
<div class="name">水果名:{{item.name}}</div>
<div class="price">价格{{item.price}}</div>
</li>
=========
computed:{
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters({
product:'changeProduct'
})
}
6、mutation
mutation 必须是同步函数
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
mutations就类似事件,子组件中用this.$store.commit('事件名')
来获取
<template>
<div id="app">
<h2>product-two</h2>
<ul>
<li v-for="(item,index) in product" :key="index">
<div class="name">水果名:{{item.name}}</div>
<div class="price">价格:{{item.price}}</div>
</li>
</ul>
</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
components:{
},
data() {
return {
str:'中国'
}
},
created(){
this.decrePrice()
},
computed:{
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters({
product:'changeProduct'
})
},
watch:{
},
methods: {
decrePrice(){
return this.$store.commit('decrePrice')
}
}
};
</script>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
product:[
{name:'apple', price: 2},
{name:'banana', price: 3},
{name:'pear', price: 4},
{name:'melon', price: 5}
],
count:0,
str:'江西九江',
},
//Getter 接受 state 作为其第一个参数
getters:{
changeProduct: (state) => {
return state.product.map(val => {
return {
name: '**' + val.name + '--',
price: val.price*2
}
})
return state.product
}
},
mutations: {
decrePrice(state){
state.product.forEach(val => {
val.price -= 1
})
}
},
actions: {
},
modules: {
}
})
方法未调用前,价格分别是2 3 4 5,在乘于2,为 4 6 4 10
调用方法后,价格分别减1,为1 2 3 4 ,在乘于2 ,为2 4 6 8
提交载荷(Payload)
store.commit 传入额外的参数,即 mutation 的 载荷(payload)
methods: {
decrePrice(){
return this.$store.commit('decrePrice',2)
}
}
//index.js文件
mutations: {
decrePrice(state,n){
state.product.forEach(val => {
val.price += n
})
}
},
在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读
decrePrice(){
return this.$store.commit('decrePrice',{
amount:2
})
}
//index.js文件
mutations: {
decrePrice(state,payload){
state.product.forEach(val => {
val.price += payload.amount
})
}
},
对象风格的提交方式
提交 mutation 的另一种方式是直接使用包含 type 属性的对象:
store.commit({
type: 'increment',
amount: 10
})
当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
7、action
Action 类似于 mutation,不同在于:
(1)Action 提交的是 mutation
,而不是直接变更状态。
(2)Action 可以包含任意异步操作
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit
提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。
分发dispatch action
子组件中,用this.$store.dispatch('action的名字')
来获取。
methods: {
decrePrice(){
return this.$store.dispatch('decrePriceAction')
}
}
index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
product:[
{name:'apple', price: 2},
{name:'banana', price: 3},
{name:'pear', price: 4},
{name:'melon', price: 5}
],
count:0,
str:'江西九江',
},
//Getter 接受 state 作为其第一个参数
getters:{
changeProduct: (state) => {
return state.product.map(val => {
return {
name: '**' + val.name + '--',
price: val.price*2
}
})
return state.product
}
},
mutations: {
decrePrice(state){
state.product.forEach(val => {
val.price += 2
})
}
},
actions: {
decrePriceAction(context){
setTimeout(()=>{
context.commit('decrePrice')
}, 2000)
}
},
modules: {
}
})
2s后
Actions 支持同样的载荷方式和对象方式进行分发:
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
调用异步 API 和分发多重 mutation
store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
现在你可以:
store.dispatch('actionA').then(() => {
// ...
})
在另外一个 action 中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
最后,如果我们利用 async / await,我们可以如下组合 action:
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。
8、modules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
具体参考:https://vuex.vuejs.org/zh/guide/modules.html
9、严格模式
开启严格模式,仅需在创建 store 的时候传入 strict: true:
const store = new Vuex.Store({
// ...
strict: true
})
在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到。
#开发环境与发布环境
不要在发布环境下启用严格模式!严格模式会深度监测状态树来检测不合规的状态变更——请确保在发布环境下关闭严格模式,以避免性能损失。