
Vue3 Router params in Class component
Recently I started to learn and program some simple demo applications (advertisement portal) in Vuejs. As an Angular developer, I am surprised by the number of ways Vue offers to achieve the desired goal. I think it is sometimes good, sometimes bad, to have multiple possibilities. Vue offers multiple approaches how to making components. Recently Vue developers add a new feature called the Vue Class component. It is the approach how to making Vue components using ES6 classes, it means using inheritance, methods, properties, and all OOP principles. It is great for me, It is more intuitive for me than plain Javascript composition API or options API.
However, when there is the great Class component feature, documentation and guides are still written using old principles and it is hard for newcomers to join principles together. At least it was hard for me. I was completely lost on how to access router params of the Vue router in the Class component and how to define these params. I needed to experiment a bit because I was unable to find a solution that fits me. I mean Vue3 application using Typescript, Vue class component, and Vue router.
Router params in class component simple solution
Yes, it was hard for me, but the completed solution is quite simple. We need to define a route as follows:
{path: '/edit-advertisement/:id', name: 'Edit Advertisement', component: EditAdvertisement, props: true}
We defined route param placeholder in the path using :id and also it is important to set props property to true. Props property means that the router parameter will be passed to the Vue component as a property (surprisingly). Then in your Vue class component, you can access it:
import { Options, Vue } from 'vue-class-component';
@Options({
props: {
id: String
}
})
export default class EditAdvertisement extends Vue {
mounted() {
console.log(this.id);
}
}
We defined id prop in Options decorator. If you do this, you can access this router param in this class using this keyword. Exactly the same as normal component props. So if you type <APP_URL>/edit-advertisement/1 you get 1 in your component.
As you can see, it was quite a simple solution, but when I started to learn Vue3 I was unable to do it because there were solutions on the internet and StackOverflow without the Vue class component and, to be honest, I was confused from the number of possibilities that did not work together.