1、下载
npm i vue-router@3 (下载的vue2使用的 路由)
npm i vue-router (默认下载最新版的vue3使用的 路由)
2、路由配置
新建的router/index.js
import VueRouter from "vue-router"; import Vue from "vue"; Vue.use(VueRouter); //引入使用到的组件 import AboutLayout from "@/components/routerTest/AboutLayout"; import HomeLayout from "@/components/routerTest/HomeLayout"; import NewsLayout from "@/components/routerTest/NewsLayout"; export default new VueRouter({ routes: [{//一级路由 path: '/home', //路由路径 TODO 一级带有 '/' component: HomeLayout, //组件名 children: [ //二级路由 { path: 'news', // TODO 二级 不可以 带有 '/' component: NewsLayout, }] }, { path: '/about', component: AboutLayout } ] })
3、在main.js里面使用
import Vue from 'vue' import App from './App.vue' import store from "@/store"; //引入路由 import router from '@/router' Vue.config.productionTip = false new Vue({ render: h => h(App), beforeCreate() { Vue.prototype.$bus = this }, store, router }).$mount('#app')
4、创建组件
5、使用路由
<template> <div> <div> <!-- Vue中借助router-link标签实现路由的切换 --> <router-link to="/home">Home</router-link> <router-link to="/About">About</router-link> </div> <div > <!-- 指定组件的呈现位置 --> <router-view></router-view> </div> </div> </template> <script> export default { name: "H", data() { return {} } } </script> <style> </style>