5

Vue Router4 的相对之前的变化

 3 years ago
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.
neoserver,ios ssh client
时间: 2021-07-30阅读: 16标签: 路由分享

扫一扫分享

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);

原文:https://vuejsdevelopers.com/topics/vue-router/

站长推荐

1.云服务推荐: 国内主流云服务商,各类云产品的最新活动,优惠券领取。地址:阿里云腾讯云华为云

链接: http://www.fly63.com/article/detial/10589


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK