首先需要安装vuex
npm install vuex
然后新建一个在src文件夹下面创建一个store文件夹,在store文件下面创建store.js文件
在文件中写上
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
开始创建状态
export const store = new Vue.Store({
store:{
products:[
{ name:"abcd",price:100},
{ name:"abcsd",price:1020},
{ name:"abcsad",price:1010},
]
}
});
创建好store.js文件之后,需要在main.js里面调用,以致于所有文件都可以共享该状态
import {store} from './store/store'
然后在vue实例里面加上
new Vue({
store:store
})
之后,如果我们想使用store存储的状态值,我们可以在那个组件页面中computed里面获取
computed:{
products(){
return this.$store.state.products;
}
}
下面是getters
在store.js文件定义一个getters,该方法可以获取store的状态值并加以处理
如
getters:{
saleProducts:state=>{
let saleProduct = state.product.map(product=>{
return {
name:"xxx"+product.name+"xxx",
price:'product/2
}
});
return saleProduct;
}
}
然后我们就可以在组件中使用
computed:{
saleProducts(){
retrun this.$store.getters.saleProducts;
}
}
mutatations 通常用来控制状态值的改变,在store.js文件中
mutations:{
reducePrice:state=>{
state.product.froeach(product=>{
product.price-=1;
})
}
}
然后在组件methods里面
mthods:{
reducePrice:function(){
this.$store.commit("reducePrice");
}
}
actions
我们可以修改一下上面的mutations,可以让他每次减少我们传进去的值
mutations:{
reducePrice:(state,payload)=>{
state.price.foreach(product=>{
product.price-=payload;
})
}
},
atcions:{
reducePrice:(context,amopunt)=>{
setTimeour(function(){
context.commit("reducePrice",payload);
},1000)
}
}
然后在组件页面中
<button @click="reducePrice(4)">reducePrice
在methods:
methods:{
reducePrice:function(amount){
this.$store.dispatch("reducePrice",amount)
}
}
我们还可以采用简写的方式进行使用mapActions和mapGetters
在组件页面中
import {mapActions} from 'vuex';
import {mapGetters} from 'vuex';
然后在computed:{
...mapGetters(["salePrice"]);
}
在mthods里面写上
methods:{
...mapActions(["reducePrice"]);
}