Tou*_*uha 6 javascript vue-router vuejs2
我正在尝试使用链接传递字符串参数。但似乎计算或方法属性不能返回参数值。当我使用计算属性时,整个组件停止渲染。
如果我直接放在{{ $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>
Run Code Online (Sandbox Code Playgroud)
来自 router.js 文件:
{
path: "/:category",
name: "category",
props: true,
component: () => import("./views/Shops.vue")
},
Run Code Online (Sandbox Code Playgroud)
我没有在控制台中收到任何错误消息。
Sat*_*hak 10
您面临这种情况error是因为箭头函数不会绑定this到vue您为其定义computed属性的实例。如果您要methods使用arrow函数进行定义,也会发生同样的情况。
不要使用箭头函数来定义方法/计算属性,this将不起作用。
只需更换
category: () => {
return this.$route.params.category;
}
Run Code Online (Sandbox Code Playgroud)
和:
category() {
return this.$route.params.category;
}
Run Code Online (Sandbox Code Playgroud)
参考 - https://vuejs.org/v2/guide/instance.html#Data-and-Methods