This post was first posted on my blog
Hi. In this post I’ll show how to pass data to a router-link in Vue.JS. Let’s assume we have a Vue project created by vue-cli. We have one component its called HelloWorld. By default there is a one component named HelloWorld. We will create new component named Profile.
For example you don’t want to use query strings like this:
https://localhost/#/profile/2
You can use params as props without query strings. Let’s start.
Creating Profile.vue Component
I’ll create a Vue component named Profile.vue. It will like this:
<template>
<div>
{{ welcome }}
</div>
</template>
<script>
export default {
name: 'Profile',
props: ['msg'],
data() {
return {
welcome: 'This is your profile'
}
},
mounted() {
if (this.msg) {
this.welcome = this.msg
}
}
}
</script>
Above code contains prop named msg and above code returns an object named welcome. When someone open this page as directly should see This is your profile message. What if someone coming from another route?
Modification in HelloWorld.vue
Let’s think about someone coming from another route thanks to router-link. Our component should like this:
<template>
<div class="hello">
<router-link :to="{ name: 'Profile', params: { msg } }">
Go to your profile
</router-link>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: `This is Ali's profile`
}
}
}
</script>
In above code, we have msg object to pass it to another route. When someone click to Go to your profile link, the page will redirect to http://localhost:8080/#/profile page. But we will not see any data when check to the Vue DevTools. Because we didn’t configure router file.
Configuration of the Router File
Router file should like this:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Profile from '@/components/Profile'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/profile',
name: 'Profile',
component: Profile,
props: true
}
]
})
As we see the profile route has the props key and it’s value equals true. Let’s check to the Vue DevTools.
What if the route configuration was like this
{
path: '/profile',
name: 'Profile',
component: Profile,
props: false
}
It will not pass data.
Thank you for reading. I hope this post will help you. You can visit the Vue Router website to get more detail.
Top comments (4)
Thank you for the tutorial!
One comment for those, who also struggle with this:
The router param didn't passed for me, because I used :to="path:..." instead of :to="name:...".
With name, it works, with path, it isn't!
clear tutorial, thanks
Thanks for this.