一、 router/index.js
// 引入路由
// eslint-disable-next-line no-unused-vars
import Vue from 'vue'
import VueRouter from 'vue-router'
import Box_1 from '../pages/Box_1.vue'
import Box_2 from '../pages/Box_2.vue'
import Menu_1 from '../pages/Menu_1.vue'
import Menu_2 from '../pages/Menu_2.vue'
Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
// 创建一个路由器
export default new VueRouter({
routes: [
{
path: '/Box_1',
component: Box_1,
children: [
{
name: 'myMenu', // 用name代替路径
path: 'Menu_1',
component: Menu_1,
props($route){
return{
id:$route.params.id,
name:$route.params.name,
}
}
},
{
path: 'Menu_2',
component: Menu_2
},
]
},
{
path: '/Box_2',
component: Box_2,
children: [
{
path: 'Menu_1',
component: Menu_1
},
{
path: 'Menu_2',
component: Menu_2
},
]
},
]
})
2、box_1.vue
<template>
<div class="m_box">
<div class="top">
<!-- 路由跳转链接 -->
<router-link
replace
class="box_1"
active-class="active"
:to="{
name: 'myMenu',
params: {
id: id,
name: name,
},
}"
>
菜单1
</router-link>
<!-- 路由跳转链接 -->
<router-link
replace
class="box_2"
to="/Box_1/menu_2"
active-class="active"
>
菜单2
</router-link>
<!-- <button @click="justTo">编程式路由跳转</button> -->
<button class="box_3" @click="justTo">编程路由跳转</button>
</div>
<div class="bottom">
<!-- 我是Box_1组件! -->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: "Box_1",
data() {
return {
id: "666",
name: "我是Box_1组件传过来的参数",
};
},
methods: {
justTo() {
console.log(this.$router);
this.$router.push({
name: "myMenu",
params: {
id: this.id,
name: this.name,
},
});
// alert("aaaa");
},
},
};
</script>
3、Menu_1.vue
<template>
<div class="m_box">{
{id}}.{
{name}}</div>
</template>
<script>
export default {
name: "Menu_1",
props:['id','name'],
mounted() {
console.log("=============");
console.log(this);
},
};
</script>
二、当出现重复异常错误
出现vue-router.esm.js?3423:2065 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/Box_1/Menu_1".
解决办法:
增加:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}