路由传参方式两种?query和params
query传参
Profile.vue
<div>
<ul>
<li v-for="m in messageList" :key="m.id" >
//(跳转路由并携带query传参,to的字符串写法)
<router-link to="`/home/profile/detail?id=${m.id}&title=${m.title}`"> </router-link>
//(跳转路由并携带query传参,to的对象写法)
<router-link to="{
name:'detail', //或者path:'/home/profile/detail'
query:{
id:m.id,
title:m.title
}
}
"> </router-link>
</li>
</ul>
<router-view></router-view>
</div>
export default {
data(){
return {
messageList:[
{
id:'001',title:'消息1',
},
{
id:'002',title:'消息2',
},
{
id:'003',title:'消息3',
}
]
}
}
}
//创建并暴露一个路由器
const routes = [{
path: '/',
redirect: '/home'
},
{
path: '/home',
name: 'home',
component: Home,
children: [{
path: 'profile',
component: Profile,
children: [{
path: 'detail',
name:'detail',
component: Detail,
}]
}, {
path: 'list',
component: Post
}, ]
},
]
//路由器
const router = new VueRouter({
routes
})
export default router
detail.vue
<template>
<ul>
<li>详情{{this.$route.query.id}}</li>
<li>主题{{this.$route.query.title}}</li>
</ul>
</template>
<script>
export default {
mounted(){
console.log('====================================');
console.log(this.$route);
console.log('====================================');
}
}
</script>
<style>
</style>
params传参
Profile.vue
<div>
<ul>
<li v-for="m in messageList" :key="m.id" >
//(跳转路由并携带params传参,to的字符串写法)
<router-link to="`/home/profile/detail/{m.id}/${m.title}`"> </router-link>
//(跳转路由并携带query传参,to的对象写法)
<router-link to="{
name:'detail', //params只能和name搭配
id:m.id,
title:m.title
}
}
"> </router-link>
</li>
</ul>
<router-view></router-view>
</div>
export default {
data(){
return {
messageList:[
{
id:'001',title:'消息1',
},
{
id:'002',title:'消息2',
},
{
id:'003',title:'消息3',
}
]
}
}
}
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import Abstract from '../views/Abstract.vue'
import Profile from '../views/User/Profile.vue'
import Post from '../views/User/Post.vue'
import Detail from '../views/User/detail.vue'
import News from '../views/components/News.vue'
Vue.use(VueRouter)
//创建并暴露一个路由器
const routes = [{
path: '/',
redirect: '/home'
},
{
path: '/home',
name: 'home',
component: Home,
children: [{
path: 'profile',
component: Profile,
children: [{
path: 'detail/:id/:title', //路由跳转params传参,to的字符串、对象形式
name:'detail',
component: Detail,
}]
}, {
path: 'list',
component: Post
}, ]
}
]
//路由器
const router = new VueRouter({
routes
})
export default router
detail.vue
<template>
<ul>
<li>详情{{this.$route.params.id}}</li>
<li>主题{{this.$route.params.title}}</li>
</ul>
</template>
<script>
export default {
mounted(){
console.log('====================================');
console.log(this.$route);
console.log('====================================');
}
}
</script>
<style>
</style>