router路由基本配置
/* 导入Vue构造函数 */
import Vue from 'vue'
/* 导入VueRouter构造函数 */
import VueRouter from 'vue-router'
/* 导入HomeView页面 */
import HomeView from '../views/HomeView.vue'
/* 调用构造函数Vue的use方法 传入VueRouter构造函数
作用是:把VueRouter当作一个插件 全局插入到Vue中*/
Vue.use(VueRouter)
/* 定义一个路由数组对象 */
const routes = [
/* 一个对象就对应了一个路由
path就是路由的地址
name给路由起个名字
component就是具体跳转的页面
*/
{
/* path: '/' 表示根路径 一进入页面跳转的组件 */
path: '/',
name: 'home',
/* 这种方式一进入页面就会全部加载,不是用到的时候再加载
性能没有懒加载方式好 */
component: HomeView,
/* 可以使用redirect重定向 一进入主页就展示第一个子页面
redirect后面跟的是路径名 */
/* 因为/是根路径 所以可以直接写one */
redirect:'/one',
children:[{
path:'one',
name:'one',
component: () => import('../views/OneView.vue')
}]
},
{
/* 这里是一级目录所以可以加/ /表示根目录 */
path: '/about',
name: 'about',
/* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
component: () => import('../views/AboutView.vue'),
/* about不是根路径 所以redirect后面的路径要写全/about/aboutchild */
redirect:'/about/aboutchild',
children:[{
path:'aboutchild',
name:'aboutchild',
component: () => import('../views/AboutChild.vue'),
}]
},
{
path: '/childa',
name: 'childa',
/* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
component: () => import('../views/ChildA.vue')
},
{
path: '/childb',
name: 'childb',
/* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
component: () => import('../views/ChildB.vue')
},
{
/* path: '*'按照常理要放在最后 ★ */
/* path: '*' 表示上面的路由没有匹配到 则进入下面的页面 */
path: '*',
name: 'notfound',
/* 懒加载 一开始的时候不加载 当你切换的这个路由的时候再加载 */
component: () => import('../views/NotFound.vue')
},
]
/* 实例化构造函数VueRouter 产生一个实例化对象router
并把上面的路由数组对象routes当作参数 以对象的方式传给构造函数VueRouter*/
const router = new VueRouter({
routes:routes
})
/* 把实例化路由对象router默认导出 */
export default router
路由基本使用
<template>
<div id="app">
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/childA">ChildA</router-link> |
<router-link to="/ChildB">ChildB</router-link>
</nav>
<router-view/>
</div>
</template>