vue-router路由嵌套的使用,以及子路由中设置默认路由:
项目结构:
在/src/App.vue文件中:
<template> <div id="app"> <router-link to="/">首页</router-link> <router-link to="/news">新闻</router-link> <router-view/> </div> </template> <script> export default { name: 'App' } </script> <style> </style>
在HellowWorld.vue文件中:
<template> <div class="hello"> hello </div> </template> <script> export default { beforeRouteEnter (to, from, next) { console.log('/ beforeRouteEnter'); next(); }, beforeRouteLeave (to, from, next) { console.log('/ beforeRouteLeave'); next(); }, name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
在News.vue文件中:
<template> <div class="news"> <router-link to="/news/cn">国内新闻</router-link> <router-link to="/news/inter">国际新闻</router-link> <router-view></router-view> </div> </template> <script> export default { } </script> <style> .news{ margin:30px auto; 300px; } </style>
在Cn.vue文件中:
<template> <div class="cn"> 国内新闻 </div> </template> <script> export default { } </script> <style> </style>
在Inter.vue文件中:
<template> <div class="inter"> inter国际 </div> </template> <script> export default { } </script> <style> </style>
在/router/index.js文件中,使用路由嵌套:
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: ()=>import(/* webpackChunkName 'home' */'@/components/HelloWorld'), beforeRouteEnter (to, from, next) { console.log('router / beforeRouteEnter'); next(); }, beforeRouteLeave (to, from, next) { console.log('router / beforeRouteLeave'); next(); }, beforeEnter: (to, from, next) => { console.log('router / beforeEnter'); next(); } }, { path: '/news', name: 'News', component: ()=>import(/* webpackChunkName 'News' */'@/components/News'), children:[ { path:'cn', name: 'cn', component: ()=>import(/* webpackChunkName 'cn' */'@/components/Cn'), }, { path:'inter', name: 'inter', component: ()=>import(/* webpackChunkName 'inter' */'@/components/Inter'), }, {path: '/news', redirect: 'cn'}, ] }, ] })
效果如下: