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. 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:
{
path: "/:category",
name: "category",
props: true,
component: () => import("./views/Shops.vue")
},
I did't get any error message in the console.
Answer
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. The same would happen if you were to define methods
using an arrow
function.
Don't use arrow functions to define methods/computed properties, this
will not work.
Just replace
category: () => {
return this.$route.params.category;
}
With:
category() {
return this.$route.params.category;
}
Refer - https://vuejs.org/v2/guide/instance.html#Data-and-Methods
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM