[英]vue.js: can't access to router parameters from computed property
I'm trying to pass a string parameter using the link.我正在尝试使用链接传递字符串参数。 but it seems that computed or methods property cannot return the parameter value.
但似乎计算或方法属性无法返回参数值。 The whole component stops rendering when I use computed property.
当我使用计算属性时,整个组件停止渲染。
If I directly put {{ $route.params.**** }}
on the template, everything works fine.如果我直接将
{{ $route.params.**** }}
放在模板上,一切正常。 But that's not the way I want.但这不是我想要的方式。
<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>
from router.js file:来自 router.js 文件:
{
path: "/:category",
name: "category",
props: true,
component: () => import("./views/Shops.vue")
},
I did't get any error message in the console.我在控制台中没有收到任何错误消息。
You are facing this error
because an arrow function wouldn't bind this
to the vue
instance for which you are defining the computed
property.您正面临此
error
,因为箭头函数不会将this
绑定到您为其定义computed
属性的vue
实例。 The same would happen if you were to define methods
using an arrow
function.如果您要使用
arrow
函数定义methods
,也会发生同样的情况。
Don't use arrow functions to define methods/computed properties, this
will not work.不要使用箭头函数来定义方法/计算属性,
this
是行不通的。
Just replace只需更换
category: () => {
return this.$route.params.category;
}
With:和:
category() {
return this.$route.params.category;
}
Refer - https://v2.vuejs.org/v2/guide/instance.html#Data-and-Methods参考 - https://v2.vuejs.org/v2/guide/instance.html#Data-and-Methods
Try with尝试
category(){
return this.$route.params.category;
}
or或者
category: function() {
return this.$route.params.category;
}
this
is not the same in arrow functions than in plain functions: https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26箭头函数与普通函数不同: https :
this
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.