[英]vue.js: can't access to router parameters from computed property
我正在尝试使用链接传递字符串参数。 但似乎计算或方法属性无法返回参数值。 当我使用计算属性时,整个组件停止渲染。
如果我直接将{{ $route.params.**** }}
放在模板上,一切正常。 但这不是我想要的方式。
<template>
<div class="container my-5 py-5">
<div class="row">{{ category }}</div>
<!-- <div class="row">{{ $route.params.category }}</div> -->
</div>
</template>
<script>
export default {
name: "shops",
data() {
return {};
},
computed: {
category: () => {
return this.$route.params.category;
}
}
};
</script>
来自 router.js 文件:
{
path: "/:category",
name: "category",
props: true,
component: () => import("./views/Shops.vue")
},
我在控制台中没有收到任何错误消息。
您正面临此error
,因为箭头函数不会将this
绑定到您为其定义computed
属性的vue
实例。 如果您要使用arrow
函数定义methods
,也会发生同样的情况。
不要使用箭头函数来定义方法/计算属性, this
是行不通的。
只需更换
category: () => {
return this.$route.params.category;
}
和:
category() {
return this.$route.params.category;
}
参考 - https://v2.vuejs.org/v2/guide/instance.html#Data-and-Methods
尝试
category(){
return this.$route.params.category;
}
或者
category: function() {
return this.$route.params.category;
}
箭头函数与普通函数不同: https : this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.