簡體   English   中英

計算屬性不適用於路由參數

[英]computed property doesn't work with route param

我有一個 getter,所有產品都存儲在那里,當我只想根據this.$route.params.id動態獲取一個產品時,它不返回任何值

當我導航到某個產品時,此代碼可以正常工作,但是當我刷新頁面時,我丟失了所有內容

computed: {
        ...mapGetters(["getAllProducts"]),
        product() {
            return this.getAllProducts.filter(item => {
                return  item.id === this.$route.params.id;
            });
        }
    }

但是如果我提供了帶有靜態值的filter()而不是this.$route.params.id就像下面這樣

        product() {
            return this.getAllProducts.filter(item => {
                return  item.id === 1;
            });
        }

我真的不知道有什么問題,盡管在我項目的另一個組件中我對一些計算屬性做了一些過濾並且它起作用了

更新:路由配置

{
    path: "/product/:id",
    name: "product-page",
    component: ProductPage,
    props: true
}

路由參數通常被解析為字符串。 嘗試將路由參數值轉換為數字類型,然后進行匹配:

product() {
    return this.getAllProducts
      .filter(item => item.id === Number(this.$route.params.id));
}

根據官方文檔

props設置為trueroute.params將設置為組件 props

所以將id添加到你的道具中,然后使用它而不是this.$route.params.id

props:['id'], //refers to this.$route.params.id
...
computed: {
        ...mapGetters(["getAllProducts"]),
        product() {
            return this.getAllProducts.filter(item => {
                return  item.id == this.id;
            });
        }
    }

嘗試將 this.$route.params.id 作為計算屬性。 然后在過濾器方法中調用它。

computed: {
    ...mapGetters(["getAllProducts"]),
    routerId() {
     return this.$route.params.id;
    },
    product() {
        return this.getAllProducts.filter(item => {
            return  item.id === this.routerId;
        });
    }
}

暫無
暫無

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

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