vuex 的使用

//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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值