【问题标题】:computed property doesn't work with route param计算属性不适用于路由参数
【发布时间】:2021-02-28 13:48:50
【问题描述】:

我有一个 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
}

【问题讨论】:

  • console.log(this.$route.params.id;) 在 product() 方法中的结果是什么?
  • 这取决于我导航到的产品。它按预期返回数字。
  • 能否在product()方法的第一个添加const _self = this,并在filter method()中调用_self.$route.params.id?
  • 我试过了。还是不行。
  • 请分享路线配置

标签: javascript html vue.js vuejs2 vue-router


【解决方案1】:

路由参数通常被解析为字符串。 尝试将路由参数值转换为数字类型,然后进行匹配:

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

【讨论】:

  • 你不应该解析这个数字。你应该只转换它的类型。换句话说,您应该使用Number(x) 而不是parseInt(x, 10)。另请注意+x 等同于使用Number(x) - 它们基本上使用相同的代码,在引擎盖下。
【解决方案2】:

根据official docs

props设置为true时,route.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;
            });
        }
    }

【讨论】:

  • 没错,组件接受 id 作为 prod,但代码仍然不起作用
  • 你试过没有props:truethis.$route.params.id
  • 试用return item.id == this.id; 而不是return item.id === this.id; 删除一个= 以禁用严格比较
【解决方案3】:

尝试将 this.$route.params.id 作为计算属性。然后在filter方法中调用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2022-11-01
    • 1970-01-01
    相关资源
    最近更新 更多