简体   繁体   中英

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

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

        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 props

so add the id to your props like then use it instead of 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. 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;
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM