繁体   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