更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
当触发事件时使用mutation,而不是computed或getters
使用vuex前:
将点击事件卸载子组件里,但是不便于调试bug,因为控制台看不出来此事件是在哪里触发的
用mutationkeyi 追查到此函数的作用。
// productListOne.vue
<template>
<div id="product-list-one">
<h2>Product-List-One</h2>
<ul>
<li v-for="product in saleProducts">
<span class="name">{{product.name}}</span>
<span class="price">${{product.price}}</span>
</li>
</ul>
<button @click="reducePrice">商品降价</button> // 点击事件
</div>
</template>
<script>
export default {
// 通过调用方法获取store.js里的数据
computed: {
products() {
return this.$store.state.products
},
saleProducts() {
return this.$store.getters.saleProducts;
}
},
methods: { // 在methods里添加事件
reducePrice: function(){
this.$store.state.products.forEach(product => {
product.price -= 1;
});
}
}
}
</script>
使用vuex-mutations后:
在store.js中添加mutations函数,在点用函数的子组件中,通过this.$store.commit('函数名')激活要触发的函数,
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
// 通过use让vue使用vuex
Vue.use(Vuex)
// 设定store,必须通过export暴露出去
export const store = new Vuex.Store({
state: {
products:[
{name:"马云",price:200},
{name:"马化腾",price:140},
{name:"马冬梅",price:20},
{name:"马蓉",price:10},
]
},
getters: {
saleProducts: (state) => {
var saleProducts = state.products.map(product =>{
return {
name: "**" + product.name + "**",
price: product.price / 2
};
});
return saleProducts
}
},
mutations:{ // 事件函数 变更状态
reducePrice: (state) => {
state.products.forEach(product => {
product.price -= 1;
});
}
}
});
// productListOne.vue
<template>
<div id="product-list-one">
<h2>Product-List-One</h2>
<ul>
<li v-for="product in saleProducts">
<span class="name">{{product.name}}</span>
<span class="price">${{product.price}}</span>
</li>
</ul>
<button @click="reducePrice">商品降价</button>
</div>
</template>
<script>
export default {
// 通过调用方法获取store.js里的数据
computed: {
products() {
return this.$store.state.products
},
saleProducts() {
return this.$store.getters.saleProducts;
}
},
methods: {
reducePrice: function(){
// this.$store.state.products.forEach(product => {
// product.price -= 1;
// });
this.$store.commit('reducePrice') // 通过commit激活store.js里的mutations函数
}
}
}
</script>
总结: 不用mutations也可以实现效果,但有两种弊端:
1. 点击事件时,控制台不会有对应响应,不知道是哪个函数触发的,不利于debug
2. 严格模式下,第一种方法会报错。