

Vue Router4 的相对之前的变化
source link: http://www.fly63.com/article/detial/10589
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

扫一扫分享
vue Router 4 已经发布了,我们来看看新版本中有哪些很酷的特性。
vue3 支持
Vue 3 引入了createApp API,该API更改了将插件添加到Vue实例的方式。 因此,以前版本的Vue Router将与Vue3不兼容。
Vue Router 4 引入了createRouter API,该API创建了一个可以在Vue3中安装 router 实例。
// src/router/index.js
import { createRouter } from "vue-router";
export default createRouter({
routes: [...],
});
// src/main.js
import { createApp } from "vue";
import router from "./router";
const app = createApp({});
app.use(router);
app.mount("#app");
History 选项
在 Vue Router的早期版本中,我们可以mode 属性来指定路由的模式。
hash 模式使用URL哈希来模拟完整的URL,以便在URL更改时不会重新加载页面。 history 模式利用 html5 History API 来实现URL导航,也是无需重新加载页面。
// Vue Router 3
const router = new VueRouter({
mode: "history",
routes: [...]
});
在Vue Router 4中,这些模式已被抽象到模块中,可以将其导入并分配给新的history 选项。 这种额外的灵活性让我们可以根据需要自定义路由器。
// Vue Router 4
import { createRouter, createWebHistory } from "vue-router";
export default createRouter({
history: createWebHistory(),
routes: [],
});
Vue Router 4 提供了addRoute 方法实现动态路由。
这个方法平时比较少用到,但是确实有一些有趣的用例。 例如,假设我们要为文件系统应用程序创建UI,并且要动态添加路径。 我们可以按照以下方式进行操作:
methods: {
uploadComplete (id) {
router.addRoute({
path: `/uploads/${id}`,
name: `upload-${id}`,
component: FileInfo
});
}
}
我们还可以使用以下相关方法:
- removeRoute
- hasRoute
- getRoutes
导航守卫可以返回值并非next
导航守卫是Vue Router的钩子,允许用户在跳转之前或之后运行自定义逻辑,例如 beforeEach,beforeRouterEnter等。
它们通常用于检查用户是否有权访问某个页面,验证动态路由参数或销毁侦听器。
在版本4中,我们可以从hook 方法中中返回值或Promise。 这样可以方便快捷地进行如下操作:
// Vue Router 3
router.beforeEach((to, from, next) => {
if (!isAuthenticated) {
next(false);
}
else {
next();
}
})
// Vue Router 4
router.beforeEach(() => isAuthenticated);
Recommend
-
100
在找一份相对完整的Webpack项目配置指南么?这里有
-
81
cd rm
-
6
Vue 3.0 会有哪些变化 发表于 2019-06-29
-
8
作者:Matt Maribojoc译者:前端小智来源:stackabuse有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。本文 GitHub
-
3
用这招监听 Vue 的插槽变化作者:Dmitri Pavlutin译者:前端小智来源:Dmitri Pavlutin有梦想,有干货,微信搜索 【大...
-
8
V2EX › 程序员 vue 无法监听实例内部修改的变化 zhaojingfeng · 2 小时 26...
-
4
vue-router4 |name的作用|query传参|parmas传参|动态路由参数|命名视图|别名alias|前置路由守卫|路由过渡效果|滚动行为 vue-router4 出现 No match found for locat...
-
5
← 今日好价 0903majer @ 2022.09.03 , 10:43
-
11
使用相对路径发布vue-cli项目的坑2017-09-08-2023-12-04561-3m使用vue-cli可以快速创建一个webpack项目脚手架,有相当多的项目都使用了相似的配置...
-
5
为什么要这样做?原生 localStorage 只能监听同源跨不同页面的变化。然而,对于单页面应用程序来说,这种方式并不实用。因此,我打算创建一个自定义钩子来监视 localStorage 中的变化。我们需要重写 localStorage 下的所有方法,以便无...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK