store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
lists: [{
id: 1,
name: '你好,Vuex',
money: 122
}]
},
getters: {
lists2: (state) => {
var numArr = state.lists.map(num => {
return {
id: new Date(),
name: "**" + num.name + "**",
money: num.money / 2
}
})
return numArr
}
},
mutations: {
reducePriceM: (state, payload) => {
state.lists.forEach(num => {
num.money -= payload;
})
}
},
actions: {
//payload是参数,可以是对象
reducePriceA: (context, payload) => {
context.commit('reducePriceM', payload)
}
}
})
调用方式如下:
Test.vue
<template>
<div>
<div v-for="(item,index) in lists" :key="index">{{item.name}} {{item.money}} </div>
<button @click="reducePriceA(4)">商品降价</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapActions} from 'vuex'
export default {
computed: {
...mapState({
lists:state => state.lists
}),
...mapGetters([
"lists2"
])
},
methods: {
...mapActions([
"reducePriceA"
])
}
}
</script>
<style>
</style>
如果没有写mapState,可以获取state中的属性值,
computed:{
lists() {
console.log(this.$store)
return this.$store.state.lists
}
}
如果在store.js中没有写mapGetters,我们可以使用如下方式获取getters:
computed:{
lists2() {
return this.$store.getters.lists2;
}
}
如果没有在store.js中写mutations:
computed:{
lists2() {
var numArr = this.$store.state.lists.map(num => {
return {
id: new Date(),
name: "**"+num.name+"**",
money: num.money / 2
}
})
return numArr
}
}
没有写mapActions:可以使用如下:
methods:{
reducePriceX(amount) {
/* this.$store.state.lists.forEach(num=>{
num.money-=1;
}) */
this.$store.commit('reducePrice')
this.$store.dispatch("reducePriceA", amount); //分发actions
}
}
注意:
对象展开运算符什么时候使用:
mapState、mapGetters、mapActions