main.js
import Vue from 'vue'
import App from './App'
import Vuex from 'vuex'
Vue.use(Vuex);
Vue.config.productionTip = false;
const store = new Vuex.Store({
state:{
products:[
{name:'苹果',price:6},
{name:'草莓',price:10},
{name:'火龙果',price:4},
{name:'芒果',price:12.5},
{name:'橘子',price:3.9}
],
},
getters:{
saleProducts:(state)=>{
return state.products.map(p=>{
return {
name:p.name,
price:p.price/2
}
})
}
},
mutations:{
riseInPrice(state,payload){
state.products.forEach(p=>{
p.price-=payload;
})
},
},
actions:{
//Action 函数不是直接变更状态,所以他没有state参数
riseInPriceAsync(context,payload){
//Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
setTimeout(()=>{
context.commit('riseInPrice',payload);
},2000)
}
}
});
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
});
App.vue
<template>
<div id="app">
<ProductListOne></ProductListOne>
<ProductListTwo></ProductListTwo>
</div>
</template>
<script>
import ProductListOne from "./components/ProductListOne";
import ProductListTwo from "./components/ProductListTwo";
export default {
name: 'App',
components: {
ProductListTwo,
ProductListOne
}
}
</script>
<style>
</style>
ProductListOne.vue
<template>
<fieldset>
<legend><h1>商品列表一</h1></legend>
<ul>
<li v-for="pro in $store.state.products">
<span>{{pro.name}}</span>
<span>{{pro.price}}</span>
</li>
</ul>
<hr>
<ul>
<li v-for="pro in $store.getters.saleProducts">
<span>{{pro.name}}</span>
<span>{{pro.price}}</span>
</li>
</ul>
<button @click="sale">大减价</button>
<button @click="waitSale">延时减价</button>
</fieldset>
</template>
<script>
export default {
name: "ProductListOne",
methods:{
sale(){
//不能直接通过$store调用mutations里的方法。需要使用$store.commit触发mutations
//还可以给commit传入额外的参数灵活控制函数的执行
this.$store.commit('riseInPrice',0.5);
},
waitSale(){
//触发action,使用的是dispatch方法
this.$store.dispatch('riseInPriceAsync',0.3);
}
}
}
</script>
<style scoped>
</style>
ProductListTwo.vue
<template>
<fieldset>
<legend><h1>商品列表二</h1></legend>
<ul>
<li v-for="pro in products">
<span>{{pro.name}}</span>
<span>{{pro.price}}</span>
</li>
</ul>
</fieldset>
</template>
<script>
export default {
name: "ProductListTwo",
data(){
return {
products:this.$store.state.products
// products:this.$store.getters.saleProducts,
}
}
}
</script>
<style scoped>
</style>