vuex主要应用于Vue.js中管理数据状态的一个库
创建一个集中的数据存储,供程序中所有组件访问
npm install vuex --save
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store=new Vuex.Store({
//存储某数据
state:{
products:[
{name:'小云',price:200},
{name:'小红',price:300},
{name:'晓东',price:240},
{name:'腊梅',price:100}
]
},
//获取某数据
getters:{
saleProducts:(state)=>{
var saleProducts=state.products.map(
product=>{
return {
name:"**"+product.name+"**",
price:product.price/2
}
});
return saleProducts;
}
},
//触发事件更改某数据
mutations:{
reducePrice:(state,payload)=>{
state.products.forEach(
product=>{
product.price-=payload;
})
}
},
//触发事件异步更改数据/可以传参
actions:{
reducePrice:(context,payload)=>{
setTimeout(() => {
context.commit("reducePrice",payload);
}, 2000);
}
}
})
computed:{
products(){
return this.$store.state.products;
},
saleProducts(){
return this.$store.getters.saleProducts;
}
},
methods:{
reducePrice:function(amount){
//mutations
//this.$store.commit('reducePrice');
//actions
this.$store.dispatch('reducePrice',amount)
}
}
}
或者使用
安装"babel-preset-stage-*,配置babel
<script>
import {mapGetters} from 'vuex'
import {mapActions} from 'vuex'
export default {
computed:{
products(){
return this.$store.state.products;
},
...mapGetters(["saleProducts"]),
},
methods:{
...mapActions(["reducePrice"]),
}
}
</script>
网友评论