0๐
โ
I put together an example with two components and a router to show how to implement.
Router
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);
import Home from '@/components/stackoverflow/router-params-example/Home'
import Detail from '@/components/stackoverflow/router-params-example/Detail'
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/detail/:id',
name: 'detail',
component: Detail,
props: true
}
]
export default new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
Home
<template>
<div class="parent">
<h4>Home</h4>
<div class="row">
<div class="col-md-6">
<router-link class="btn btn-primary" :to="{ name: 'detail', params: { id: detailId } }">Show Detail</router-link>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
detailId: 1
}
}
}
</script>
Detail
<template>
<div class="child">
<h4>Detail</h4>
<div class="row">
<div class="col-md-6">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>USER NAME</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.username }}</td>
</tr>
</tbody>
</table>
<router-link class="btn btn-secondary" :to="{ name: 'home' }">Back</router-link>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: {
id: {
type: Number,
required: true
}
},
data() {
return {
user: {}
}
},
methods: {
getUser() {
axios.get('https://jsonplaceholder.typicode.com/users/' + this.id)
.then( response => this.user = response.data )
.catch( error => console.log(error) )
}
},
created() {
this.getUser();
}
}
</script>
Source:stackexchange.com