文件结构:
student.vue:
<template>
<div>
<h1>学生</h1>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data () {
return {
msg: '我是学生组件'
}
},
created() {
console.log(this.$route.params)
},
}
</script>
<style scoped>
</style>
teacher.vue:
<template>
<div>
<h1>老师</h1>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data () {
return {
msg: '我是老师组件'
}
},
created() {
console.log(this.$route.params)
},
}
</script>
<style scoped>
</style>
router.js:
import Vue from "vue";
import VueRouter from "vue-router";
// 引入组件
import student from '../components/student.vue'
import teacher from '../components/teacher.vue'
// 要告诉 vue 使用 vueRouter
Vue.use(VueRouter);
const routes = [
{
name:'student',
path:"/student/:id",
component: student
},
{
name:'teacher',
path: "/teacher/:id",
component: teacher
},
]
var router = new VueRouter({
routes
})
export default router;
main.js:
APP.vue
方法一,通过router-link的方式:
<template>
<div id="app">
<div>
首页<br />
<!-- 路由传参方法一 -->
<router-link :to="'/student/'+id">学生</router-link>
<router-link :to="'/teacher/'+id">老师</router-link>
</div>
<div>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'app',
data() {
return {
id: 0
}
},
}
</script>
<style scoped>
</style>
方法二通过点击事件和this.$router.push():
<template>
<div id="app">
<div>
首页<br />
<!-- 路由传参方法二 -->
<div @click="btnClick(1)">学生</div>
<div @click="btnClick(2)">老师</div>
</div>
<div>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: 'app',
methods: {
btnClick(index){
if(index == 1){
this.$router.push({
name:'student',
params:{
id:'111'
}
})
}
else{
this.$router.push({
name:'teacher',
params:{
id:'222'
}
})
}
}
},
}
</script>
<style scoped>
</style>
结果: