gpt4 book ai didi

javascript - vue.js : can't access to router parameters from computed property

转载 作者:行者123 更新时间:2023-11-30 09:14:18 25 4
gpt4 key购买 nike

我正在尝试使用链接传递字符串参数。但似乎 computed 或 methods 属性无法返回参数值。当我使用计算属性时,整个组件停止渲染。

如果我直接将 {{ $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 绑定(bind)到你正在为其定义 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

关于javascript - vue.js : can't access to router parameters from computed property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56303878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com