计算 属性 不适用于路由参数
computed property doesn't work with route param
我有一个 getter,所有产品都存储在那里,当我只想根据 this.$route.params.id
动态获取一个产品时,它 return 没有任何价值
当我导航到某个产品时,这段代码可以正常工作,但是当我刷新页面时,我失去了一切
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
}
尝试将 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;
});
}
}
根据 official docs :
When props
is set to true
, the route.params
will be set as the component 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;
});
}
}
路由参数通常被解析为字符串。
尝试将路由参数值转换为数字类型,然后进行匹配:
product() {
return this.getAllProducts
.filter(item => item.id === Number(this.$route.params.id));
}
我有一个 getter,所有产品都存储在那里,当我只想根据 this.$route.params.id
动态获取一个产品时,它 return 没有任何价值
当我导航到某个产品时,这段代码可以正常工作,但是当我刷新页面时,我失去了一切
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
}
尝试将 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;
});
}
}
根据 official docs :
When
props
is set totrue
, theroute.params
will be set as the component 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;
});
}
}
路由参数通常被解析为字符串。 尝试将路由参数值转换为数字类型,然后进行匹配:
product() {
return this.getAllProducts
.filter(item => item.id === Number(this.$route.params.id));
}