1 安装
npm install vue-router@4
2 基础使用
定义路由
router.js
import { createRouter,createWebHashHistory} from 'vue-router' import About from '../components/About.vue' const routes = [ { path: '/about', component: About }, //{ path: '/home', component: Home }, ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router
注册路由
main.js
import { createApp } from 'vue' import App from './App.vue' import router from './router/index.js' createApp(App).use(router).mount('#app')
使用路由
App.vue
<template> <!-- 创建超链接 可以在不重新加载页面的情况下更改URL--> <router-link to="/about">Go to About</router-link> <!-- 路由出口 --> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view> </template>