簡體   English   中英

無法使用操作設置狀態對象

[英]Can't set state object using action

我的 vue 應用程序上有一個產品列表和表格。 打開產品列表時,會向我的 rest api 發出請求,並將結果填充到 pinia 存儲對象 ( products ) 中。 到目前為止效果很好,產品已添加到我的狀態。

我還可以通過將product_id傳遞給它來使用我的 api 請求單個產品。 這就是我最初處理產品表單的方式,但我意識到過濾products存儲對象並從狀態中獲取單個產品比在加載表單組件時發出另一個 api 請求更有效。 我創建了一個新操作來執行此操作,但我無法讓它工作。 這是我的商店的動作:

//ProductStore.js

import { defineStore } from "pinia";
import { getProducts } from "@/composables/products";

export const useProductStore = defineStore("product", {
  state: () => ({
    products: [], //for my products list component
    product: {}, //for my product form component
    attributes: [],
    loading: false,
    error: "",
  }),
  actions: {
    findProduct(id) { //find single product in store
      this.product = this.products.find((product) => product.id === id);
    },
    async fetchProducts() { // retrieve all products from api
      this.loading = true;
      const { products, error } = await getProducts(); //api call
     
      this.products = products;
      this.error = error;
      this.loading = false;

    },
  }
});

這是我的產品表單組件,我正在嘗試過濾products商店以獲取單個product並與表單綁定:

// ProductForm.vue

<template>
 <input v-model="product.name" class="input" type="text" />
 <input v-model="product.desc" class="input" type="text" />
</template>

<script setup>
  import { onMounted } from "vue";
  import { storeToRefs } from "pinia";
  import { useProductStore } from "@/stores/ProductStore";
  
  const props = defineProps({
    id: String,
  });

  const store = useProductStore();
  const { product, error, loading } = storeToRefs(store);

  onMounted(() => {

    store.findProduct(props.id);
    console.log(product);

  });
  
</script>

當我使用console.log(product)時,我似乎得到了產品商店對象的 ref() 但沒有 value 屬性:

在此處輸入圖像描述

當我運行所有這些時,我得到錯誤: Uncaught (in promise) TypeError: $setup.product is undefined

我完全知道這是由於我對 vue 3 組合 API 和 pinia 的知識匱乏。 我不知道發生了什么事。

好吧,我想我明白了......在我的ProductForm組件中,我為product_id引入了道具:

const props = defineProps({
    id: String,
  });

我是這樣調用我的動作的:

store.findProduct(props.id);

我開始懷疑 prop 是一個字符串(因為它來自 url)是否導致了這個問題。 所以我用了:

store.findProduct(parseInt(props.id));

它立即將單個產品返回到我的組件中。 所以我最終修改了我的路由文件來為我處理解析:

//  @/routes/index.js

{
  name: "Product",
  path: "/products/:id",
  component: () => import("@/components/ProductForm"),
  props: route => ({ id: Number(route.params.id) }),
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM