npm install vue-router --save
在src目录下新建router文件夹以及index.js
在index.js写入以下代码
//1.导入Vue和VueRouter的包 import Vue from 'vue' import VueRouter from 'vue-router' //2.调用Vue.use()函数,把VueRouter安装为Vue的插件 Vue.use(VueRouter) //3.创建路由的实例对象 const router = new VueRouter() //4.向外共享路由的实例对象 export default router
在main.js导入路由包并且把路由实例对象
import Vue from 'vue' import App from './App.vue' import Axios from 'axios' import router from '@router/index.js' // 配置请求的根路径 Axios.defaults.baseURL = '/api' new Vue({ render: h => h(App), //在Vue项目中,要想把路由用起来,必须把路由实例对象,通过下面的方式进行挂载 //router:路由的实例对象 router:router }).$mount('#app')
在index.js配置路由
//1.导入Vue和VueRouter的包 import Vue from 'vue' import VueRouter from 'vue-router' import Home from '' import Home1 from '' import Home2 from '' //2.调用Vue.use()函数,把VueRouter安装为Vue的插件 Vue.use(VueRouter) const routes = [ { path: '*', redirect: '/'//重定向 }, { path: '/home', name: 'Home', //组件已经导入,直接写组件名 component: Home,//路由名字 children: [ //子路由 { path: '/d', name: 'd', component:Home1 }, { path: '/e', name: 'e', component:Home2 } ] }, { path: '/b', name: 'b', component: jianjie//路由名字 }, { path: '/c', name: 'c', //组件未导入,在这里导入组件并绑定 component: () => import( '../views/About.vue') } ] //3.创建路由的实例对象 const router = new VueRouter({ mode: 'history', routes }) //4.向外共享路由的实例对象 export default router
在界面使用路由
<template> <router-link to="/home1">点击跳转1</router-link> <router-link to="/b">点击跳转1</router-link> <router-view></router-view> </template>