Vue3 使用vue-router配置路由

Vue 官方文档(中文):介绍 | Vue.js

Vue Router 官方文档(中文):介绍 | Vue Router

1、安装vue-router

 安装指令:
$ npm install vue-router@4

或者直接下载或引用:
https://unpkg.com/vue-router@4

2、在src目录下创建router/router.js

import {
	createRouter,
	createWebHashHistory,
	createWebHistory
} from 'vue-router'

const routes = [{
		path: '/',
		redirect: '/home'
	},
	{
		path: '/home',
		name: 'home',
		component: () => import('../pages/home/home.vue'),
		meta: {
			title: 'Home'
		},
	}]

// router实例
const router = createRouter({
	history: createWebHashHistory(), //hash模式(若使用history模式改为createWebHashHistory())
	routes,
});


// 全局前置守卫
router.beforeEach((to, from, next) => {
	next();
});

// 全局解析守卫
router.beforeResolve(async to => {});

// 全局后置钩子
router.afterEach((to, from, failure) => {
	// if (!failure) sendToAnalytics(to.fullPath)
});

export default router

3、在main.ts引用:

import { createApp } from 'vue'
import router from './router/router'
import './style.css'
import App from './App.vue'

const app = createApp(App)
app..use(router)
	.mount('#app')

4、app.vue中

<template>
  <div>
	  <router-view/>
  </div>
</template>

猜你喜欢

转载自blog.csdn.net/qq_29483485/article/details/126127432