一、Vue router4.x
①创建路由
Vue2使用的是router3.x的API,换成Vue 3 需要用router4.x的API
3.x
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export const constantRoutes = [...]
const createNewRouter = () => new Router({
base: process.env.VUE_APP_BASE_URL, // 根路径
routes: constantRoutes,
mode: 'history'
})
const router = createNewRouter()
export default router
4.x
import { createRouter, createWebHistory } from 'vue-router'
export const constantRoutes = [...]
const createNewRouter = () => createRouter({
// 控制滚动 滚动行为 https://next.router.vuejs.org/zh/guide/advanced/scroll-behavior.html
// https://next.router.vuejs.org/zh/api/#scrollbehavior
scrollBehavior: () => ({ y: 0 }),
history: createWebHistory(process.env.VUE_APP_BASE_URL), // history为必填项
routes: routes
})
const router = createNewRouter()
export default router
如官方文档:
① Vue Router 不再是一个类,而是一组函数。现在你不用再写 new Router(),而是要调用 createRouter,
② history 配置取代 mode
- “history”: createWebHistory()
- “hash”: createWebHashHistory()
- “abstract”: createMemoryHistory()
③ base根路径上下文从base配置改为作为 history (createWebHistory等)的第一个参数传递