Vue 中的状态变化

问题描述 投票:0回答:1

我最近开始使用 Nuxt 并开始为在线商店制作应用程序。我通过 API 获取产品数据并使用它来创建产品卡。
而且每张卡片中都有一个按钮,按下时,所谓订购的商品数量会不断增加。我正在尝试显示此数量,但卡片中未显示产品的更改数量。

店铺:

export const state = () => ({
    categories: [],
    mensClothes: [],
    electronics: [],
    womensClothes: [],
    jeweleries: [],
})

通过API获取数据的代码:

async fetch() {
  this.goods = await this.$http.$get('https://fakestoreapi.com/products')
  for(let i = 0; i < this.goods.length; i++){
    // console.log(this.goods[i].category);
    this.$store.state.data.categories.push(this.goods[i].category)
    switch(this.goods[i].category){
      case "men's clothing":
        this.$store.state.data.mensClothes.push(this.goods[i])
        break;
      case "jewelery":
        this.$store.state.data.jeweleries.push(this.goods[i])
        break;
      case "electronics":
        this.$store.state.data.electronics.push(this.goods[i])
        break;
      default: 
      this.$store.state.data.womensClothes.push(this.goods[i])
    }
  }
  console.log(this.goods);
  this.$store.state.data.categories = new Set(this.$store.state.data.categories)
},

事件触发方式:

addToCart(event) {
  let parent = event.target.closest('.good'),
  parentId = parent.getAttribute('id');
  this.$store.state.data.mensClothes[parentId].amount++;
  this.amount = this.$store.state.data.mensClothes[parentId].amount;
  this.id = this.$store.state.data.mensClothes[parentId];
  console.log(this.$store.state.data.mensClothes[parentId].amount);
  console.log(this.$store.state.data.mensClothes[parentId]);
}

为产品添加新对象属性的代码:

created() {
  console.log(this.$store.state.data.mensClothes);
  this.$store.state.data.mensClothes.forEach(mensCloth => {
    mensCloth.amount = 0
    mensCloth.totalSum = function(){
       return this.price * this.amount
    }
    console.log(mensCloth);
  })
},

产品卡片制作代码:

<template>
  <div v-for="good in $store.state.data.mensClothes" :id="good.id" class="good">
    <div class="good-img">
      <img :src="good.image" alt="">
    </div>
    <div class="good-description">
      <p>{{good.title}}</p>
      <h5>{{good.price}}</h5>
      <div class="good-btns">
        <button class="look-btn">View product</button>
        <button class="order-btn" @click="addToCart">Add to cart</button>
      </div>
    </div>
    <p class="amount">{{good.amount}}</p>
  </div>
</template>

nuxt.js state
1个回答
0
投票

我不认为商店会触发变化,你应该为此使用

useState
ref

© www.soinside.com 2019 - 2024. All rights reserved.