简体   繁体   English

计算属性不适用于路由参数

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

I have a getter where all products are stored there, and when I want to get only one product dynamically depending on this.$route.params.id it doesn't return any value我有一个 getter,所有产品都存储在那里,当我只想根据this.$route.params.id动态获取一个产品时,它不返回任何值

this code works correctly when I navigate to a certain product, but when I refresh the page I lose everything当我导航到某个产品时,此代码可以正常工作,但是当我刷新页面时,我丢失了所有内容

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

But if I supplied filter() with static value in instead of this.$route.params.id like below it works但是如果我提供了带有静态值的filter()而不是this.$route.params.id就像下面这样

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

I really don't know what is the problem, despite of in another component in my project I did some filters on some computed properties and it worked我真的不知道有什么问题,尽管在我项目的另一个组件中我对一些计算属性做了一些过滤并且它起作用了

update: the routes config更新:路由配置

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

Route params are usually parsed as strings.路由参数通常被解析为字符串。 Try converting the route param value to number type and then do the match:尝试将路由参数值转换为数字类型,然后进行匹配:

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

According to the official docs :根据官方文档

When props is set to true , the route.params will be set as the component propsprops设置为trueroute.params将设置为组件 props

so add the id to your props like then use it instead of this.$route.params.id :所以将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;
            });
        }
    }

Try giving this.$route.params.id as a computed propertly.尝试将 this.$route.params.id 作为计算属性。 Then call it in the filter method.然后在过滤器方法中调用它。

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