mixsun'blog
~ ~ ~ ~ ~ ~
米克斯博客
License: MIT License
前言
在编写vue里的SPA(Single Page Application单页面应用)时,我们始终绕不开路由的使用,vue-router4.0版里有一些重要更新,在这里分享给大家。
什么是Vue-Router?
Vue路由器是Vue.js的官方路由器,它与Vue.js核心深度集成,使用Vue轻松构建单页应用程序变得轻而易举。功能包括:
嵌套路线映射
动态路由
模块化,基于组件的路由器配置
路由参数,查询,通配符
查看由Vue.js过渡系统提供动力的过渡效果
细粒度的导航控制
带有自动活动CSS类的链接
HTML5历史记录模式或哈希模式
可自定义的滚动行为
网址的正确编码
路由安装
css复制代码npm i vue-router@4
路由模式
createWebHistory 创建history路由模式
createWebHashHistory 创建hash路由模式
createMemoryHistory 创建基于内存的历史记录
这三种路由方式都有一个可选参数base,为每个URL前面的基本路径,默认为'/'
配置路由
javascript复制代码// router/index
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const Login = ()=> import('../views/login/login.vue')
const Home = ()=> import('../views/home/home.vue')
const About = ()=> import('../views/about/about.vue')
const routes: Array = [
{ path: '/', name: 'login', component: Login },
{ path: '/home', name: 'home', component: Home, },
{ path: '/about', name: 'about', component: About },
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
// main
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
const app = createApp(App).use(router).mount('#app')
新版路由器使用createRouter创建,RouteRecordRaw是内置的类型接口,routes改为必传参数。
路由插槽
append
event
tag
exact
上面列举的4个属性已经不再使用,可在app.config.globalProperties里自己实现全局方法,例如:
javascript复制代码// main.js
const app = createApp(App)
app.config.globalProperties.append = (path, pathToAppend) =>
path + (path.endsWith('/') ? '' : '/') + pathToAppend
// home.vue
router-link改为使用作用域插槽:
xml复制代码
现在必须通过v-slot API在router-view内部使用transition和keep-alive。
xml复制代码
现有的router.onReady函数已替换为router.isReady,该函数不接受任何参数并返回Promise,因为现在导航包含第一个都是异步的,所以如果使用transition,需要在挂载dom之前调用isReady:
scss复制代码router.isReady().then(()=> app.mount('#app'))
Vue路由和Composition API
当我们使用router-link标签时是一点毛病也没有,但是当需要编程式路由跳转的时候沙雕了,没有this咋调用router啊!难道还要再写一个methods在里面操作吗(黑人问号),还好这里咱们的router给了解决办法,看下图:
这里只需要调用对应的userRouter函数就可以了,注意要在上方import引入,在setup里面不用return返回。(这里没有贴代码,自己手动敲一下感受编程的快乐🤣)
RouterView
在一种情景下,我们可能会需要在页面中同时显示多个路由视图,而不是嵌套,那么就需要用到router-view的name属性,默认使用default:
javascript复制代码// 页面
// router/index
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
components: {
default: Home,
// 这里是es6对象增强写法
login,
// 同理
about,
},
},
],
})
components里面的组件会与router-view里面的name相对应。
scrollBehavior变化
scrollBehavior返回的对象x重命名为left,y重命名为top。
路由重定向与别名
路由重定向(redirect)就是通过各种方法将各种网络请求重新定个方向转到其它位置,如/home转到/
csharp复制代码// 路径写法
const routes = [{ path: '/home', redirect: '/' }]
// 命名写法
const routes = [{ path: '/home', redirect: { name: 'homepage' } }]
// 函数写法
const routes = [
{
path: '/search/:searchText',
redirect: to => {
return { path: '/search', query: { q: to.params.searchText } }
},
},
]
别名表示访问url时自由命名,不受约束,router会自动进行别名匹配,就像我们设置/的别名为/home,相当于访问/:
csharp复制代码const routes = [{ path: '/', component: Homepage, alias: '/home' }]
// alias是别名的key
动态路由
在一些特定场景里面我们可能会使用到动态路由,所以这里给出了使用方式,动态路由主要通过两个功能实现router.addRoute()和router.removeRoute()。
php复制代码// addRoute是添加一条新的路由路径
router.addRoute({ name: 'about', path: '/about', component: About })
// removeRoute是删除路由,注意删除后对应的子路由和别名都会删掉
router.removeRoute('about')
// 路由嵌套
router.addRoute('about', { path: 'profile', component: Profile})
//等价于
router.addRoute({
name: 'about',
path: '/about',
component: About,
children: [{ path: 'profile', component: Profile}],
})
Vue Router 提供了两个功能来查看现有的路由:
router.hasRoute:检查路由是否存在。
router.getRoutes:获取一个包含所有路由记录的数组。
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.