//store/index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
// 表示商品添加
const Add = 'ADD'
export default new Vuex.Store({
state: {
goods: [
{
id: 1,
buyCount: 1,
title: "wywuiqiyiwyqi",
price: 55,
},
{
id: 2,
buyCount: 1,
title: "dlkajdlal",
price: 10,
},
],
totalPrice: 0,
totalNum: 0,
},
getters: {
goodsObj: (state) => {
return state.goods;
},
goodsObjId: (state) => (id: any) => {
return state.goods.filter((item) => item.id === id);
},
},
mutations: {
[Add](state, {index}) {
state.goods[index].buyCount++;
state.totalNum++;
state.totalPrice += state.goods[index].price;
},
},
actions: {
increment({commit},payload){
commit(Add,payload)
}
},
modules: {},
});
// xxx页面
<template>
<div>
<div v-for="(item, index) in goods" :key="item.id">
{{ item.title }}
<span @click="handelAdd(index)">+</span>
<input type="text" v-model="item.buyCount" />
<span>-</span>
</div>
<p>总价:{{ totalPrice }}</p>
<p>总数:{{ totalNum }}</p>
</div>
<div v-for="item in this.$store.state.list" :key="item.id">
{{ item.name }}
<img :src="item.pic">
</div>
<div v-for="item in goodss" :key="item.id">
{{ item.price }}
</div
</template>
<script>
import { mapState,mapGetters } from "vuex";
export default {
data() {
return {};
},
computed: {
// goods(){
// return this.$store.state.goods
// },
...mapState(["goods"]),
...mapState({
totalPrice: (state) => state.totalPrice,
totalNum: (state) => state.totalNum,
...mapGetters(['goodsObj']),
...mapGetters({
goodss:'goodsObj'
})
}),
},
mounted() {
console.log(this.$store.getters.goodsObj);
console.log(this.$store.getters.goodsObjId(1));
axios.get('http://localhost:3000/goods').then(res=>{
console.log(res);
this.$store.state.list = res.data
},
methods: {
handelAdd(index) {
// this.$store.commit("add", index);
// this.$store.commit({
// type:'ADD',
// index
// });
this.$store.dispatch('increment',{index})
},
},
};
</script>
<style lang="scss" scoped></style>