[英]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.