vue 路由重定向

While the basics of routing in Vue.js have already been covered, today we’ll explore some other features Vue Router has to offer such as redirects and navigation guards.

尽管已经 涵盖了Vue.js中的路由基础,但今天我们将探索Vue Router必须提供的其他功能,如重定向和导航保护 。

Other advanced Vue Router topics already covered include Route Meta Fields and Nested Routes so make sure to check those out. With that said, let’s get started!

已经涵盖的其他高级Vue路由器主题包括“ 路由元字段”和“ 嵌套路由”,因此请确保将其签出。 话虽如此,让我们开始吧!

建立 (Setup)

Since this is about advanced routing features offered by Vue Router, you probably already know how to accomplish a basic setup. Just in case, here’s a bare-bones setup:

由于这是Vue Router提供的高级路由功能,您可能已经知道如何完成基本设置。 以防万一,这是一个简单的设置:

# Yarn
$ yarn add vue-router
# NPM
$ npm install vue-router --save
main.js
main.js
import Vue from 'vue';
import VueRouter from 'vue-router';Vue.use(VueRouter);const Swamp = { template: '<div>Swamp</div>' };
const Gator = { template: '<div>Gator</div>' };const router = new VueRouter({routes: [{ path: '/swamp', component: Swamp },{ path: '/gator', component: Gator }]
});const app = new Vue({router
}).$mount('#app');

重新导向 (Redirects)

There are a few ways we can accomplish redirects with Vue Router. Redirects will change the route to the intended target and reflect this change in the current URL.

我们可以通过几种方法使用Vue Router完成重定向。 重定向将更改到预期目标的路由,并将此更改反映在当前URL中。

const router = new VueRouter({routes: [{ path: '/swamp', component: Swamp },{ path: '/gator', component: Gator },{ path: '/croc', redirect: '/gator' }]
});

When a user navigates to /croc, instead they’ll be redirected to /gator and the URL in the address bar will be /gator.

当用户导航到/croc ,他们将被重定向到/gator ,而地址栏中的URL将是/gator

We can also use a function to accomplish dynamic routing:

我们还可以使用一个函数来完成动态路由:

const router = new VueRouter({routes: [{ path: '/swamp', component: Swamp },{ path: '/gator', component: Gator },{ path: '/croc', redirect: to => {return '/gator';
}}]
});

In the above code, the argument to contains the original target route object with information such as the route’s path or name.

在上面的代码中,参数to包含原始目标路线对象,并带有诸如路线的pathname

别名 (Aliases)

Aliases are like redirects but do not update the URL when the route is matched.

别名就像重定向,但在路由匹配时不会更新URL。

const router = new VueRouter({routes: [{ path: '/swamp', component: Swamp, alias: '/bayou' },{ path: '/gator', component: Gator },{ path: '/croc', redirect: to => {return '/gator';}}]
});

With the above configuration, a user navigating to /swamp will get the Swamp component with a url of /swamp. If a user instead navigates to /bayou, they’ll still get the Swamp component but the url will remain /bayou.

通过上述配置,导航到/swamp的用户将获得Swamp组件,其URL为/swamp 。 如果用户改为导航到/bayou ,他们仍然会获得Swamp组件,但网址仍为/bayou

导航卫士 (Navigation Guards)

Now that we’ve covered Redirects, let’s cover a related but more complex topic: Navigation Guards. Navigation Guards allow us to dynamically prevent navigation in vue-router via redirects or cancellation. If a user of our app doesn’t have permissions to view /admin, we can either cancel or redirect the user to an appropriate alternate route. This is important so users aren’t exposed to components that aren’t relevant to their interests.

现在我们已经介绍了重定向 ,下面我们讨论一个相关但更复杂的主题: Navigation Guards 。 导航卫士允许我们通过重定向或取消来动态阻止在vue-router导航。 如果我们应用程序的用户无权查看/admin ,我们可以取消该用户或将其重定向到适当的替代路线。 这很重要,因此用户不会接触与自己的兴趣无关的组件。

As a basic example, we can use a simple Navigation Guard to redirect a user to a login page if they are not yet authenticated:

作为一个基本示例,如果用户尚未通过身份验证,我们可以使用一个简单的Navigation Guard将用户重定向到登录页面:

const router = new VueRouter({routes: [{ path: '/swamp', component: Swamp, alias: '/bayou' },{ path: '/gator', component: Gator },{ path: '/croc', redirect: to => {return '/gator';}},{ path: '/login', name: 'login', component: Login }]
});router.beforeEach((to, from, next) => {if (to.name !== 'login' && !isAuthenticated) {next({ name: 'login' });} else {next();}
});

We can also define guards on a per-route basis:

我们还可以按路线定义防护:

const router = new VueRouter({routes: [{ path: '/swamp', component: Swamp, alias: '/bayou' },{path: '/gator',component: Gator,beforeEnter: (to, from, next) => {console.log(`${from.path} to ${to.path}?`);next();}
},{ path: '/croc', redirect: to => {return '/gator';}},{ path: '/login', name: 'login', component: Login }]
});

Make sure to only ever call next() one time or you could run into errors or incorrect path resolution!

确保仅一次调用next(),否则可能会遇到错误或错误的路径解析!

Components themselves can also enforce their own guards. One way this could be useful is to ask a user if they meant to navigate away, and cancel the navigation by passing false to next(); We also have access to the component’s this which allows us to use the component’s methods and properties in determining our routing logic.

组件本身也可以执行自己的防护措施。 一种有用的方法是询问用户是否要离开,并通过将false传递给next()来取消导航; 我们还可以访问组件的this ,这使我们可以使用组件的方法和属性来确定路由逻辑。

const Swamp = {template: '<div>Swamp</div>',beforeRouteEnter(to, from, next) {console.log('Welcome to the swamp!');next();},beforeRouteLeave(to, from, next) {const answer =window.confirm('Are you sure you want to leave?');if (answer) {next();} else {next(false);}}
};

Please remember, as this code runs in the browser a user will have access to all code for your app regardless of Navigation Guards. When working on production applications always remember to implement proper validation and permission checking on the back-end!

请记住,由于此代码在浏览器中运行,因此无论导航卫士如何,用户都可以访问您应用的所有代码。 在生产应用程序上工作时,请始终记住在后端实施适当的验证和权限检查!

结语 (Wrapping Up)

We already know Vue Router is a great solution to provide routing in your Vue app, but today we’ve covered some advanced use-cases that Vue Router supports out-of-the-box. As always, make sure to review the official documentation. Check out some other advanced features such as Transitions to spice up your app or Lazy Loading Routes to increase performance.

我们已经知道Vue Router是在您的Vue应用程序中提供路由的绝佳解决方案,但是今天我们已经介绍了Vue Router支持即用型的一些高级用例。 与往常一样,请务必查看官方文档 。 请查看其他一些高级功能,例如用于为您的应用增添趣味的“ 过渡”或“ 延迟加载路径”以提高性能。

翻译自: https://www.digitalocean.com/community/tutorials/vuejs-advanced-vue-routing

vue 路由重定向

vue 路由重定向_使用Vue和Vue路由器进行高级路由:重定向和Nav Guard相关推荐

  1. vue颜色选择器_如何制作? Vue的颜色选择器!

    vue颜色选择器 by ZAYDEK 由ZAYDEK 如何制作? Vue的颜色选择器! (How to make a ? color picker with Vue!) 注意:颜色看起来可能比实际颜色 ...

  2. baidumap vue 判断范围_懂一点前端—Vue快速入门

    01. 什么是 Vue Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架,是当下很火的一个 JavaScript MVVM 库,是以 数据驱动和组件化 的思想构建的 ...

  3. java 路由框架_使用Spring框架和AOP实现动态路由

    本文的大体思路是展示了一次业务交易如何动态地为子系统处理过程触发业务事件.本文所示的例子使用Spring框架和Spring AOP有效地解耦业务服务和子系统处理功能.现在让我们仔细看看业务需求. 业务 ...

  4. vue.js部署_如何将安全Vue.js应用程序部署到AWS

    vue.js部署 本文最初发布在Okta开发人员博客上 . 感谢您支持使SitePoint成为可能的合作伙伴. 编写Vue应用程序直观,直接,快捷. Vue具有较低的进入门槛,基于组件的方法以及诸如热 ...

  5. vue + element-ui 聊天_推荐6款Vue管理后台框架,收藏好,留备用

    Vue.js 是一个目前比较流行的前端框架,在业界也算很有名气,今天这里为大家罗列一下基于Vue的后端管理的框架. 使用这些框架你会发现它包括了我们常用的路由,状态,交互等等,我们只需要去复用它的代码 ...

  6. 2 snippets vue 修改配置_教你发布vue+.netCore项目到服务器

    最近一直在做项目,发布部署的事情都是同事或者老大做的,无奈什么事都要自己尝试经历后才能记住,所以发布的事情轮到我了,由于是第一次发布部署项目到一个新的服务器环境,难免会遇到各种各样的问题,总结下来,希 ...

  7. vue隐藏浏览器_一分钟学会Vue的条件渲染和列表渲染

    介绍 之前一段时间由于工作很忙,没有时间继续学习Vue,今天算是继续对之前的学习进行补充了,今天要学习的便是Vue的条件渲染和列表渲染,我们将讨论if.if-else.if-else-if,show等 ...

  8. vue接收索引_前端开发:Vue中findIndex() 方法的使用

    前端开发过程中对数据的遍历是非常常见的操作,在Vue.js中通过对数组下标遍历操作来进行相关逻辑处理的方法常用的有两种:some()和findIndex() ,二者都是通过遍历数组里面的id值来进行操 ...

  9. vue 图片剪辑_一个简单的Vue图片剪辑插件

    vue 图片剪辑 Vue-Crpopper (vue-crpopper) A simple picture clipping plugin for vue. 一个简单的Vue图片剪辑插件. 安装 (i ...

最新文章

  1. 高级特性-多线程,GUI
  2. C++类为什么使用private?------封装性
  3. python如何读取一个文件夹下的多个文件(夹)?
  4. linux父子进程同步实验,Linux-父子进程的简单同步
  5. caxa画图怎么倒角_16个底部含圆弧倒角的宽槽编程案例
  6. 怎么解决缺少java.doc_java 生成doc帮助文档时出现的问题
  7. Oracle 实验6 PL/SQL编程
  8. 封装成jar包_通用源码阅读指导mybatis源码详解:io包
  9. 每日英语:Foreign Tourists Skip Beijing
  10. 多家科技公司坐等维基解密共享CIA机密文件
  11. 国家统计局全国统计用区划代码和城乡划分代码Python爬虫样例
  12. java实现在线预览word(docx)功能
  13. 安卓车载中控竖屏分三屏
  14. Bin格式文件结构及其查看工具
  15. 15s是什么意思c语言,15s是什么意思
  16. ViewPager圆形指示器
  17. easyExcel导出excel文件并打包成zip压缩包下载
  18. 离职原因该怎么说才比较好 ?
  19. java编程题身高排队_编程初学者入门4_从键盘输入5个人的身高(米),求他们的平均身...
  20. Java内存模型(JMM)详解

热门文章

  1. 【飞郁2022新课程】23 - CE找偏移表达式
  2. CR渲染器全景图如何渲染颜色通道_【扮家家云渲染】3Dmax干货技巧|设置高质量室内模型渲染参数...
  3. 服务器宠物系统,你们升级我抓宠,PVX也能从剑网三怀旧服的升级热潮中找到快乐!...
  4. 异常System.Threading.Thread.AbortInternal
  5. 用css实现垂直水平居中的几种方法
  6. 2020智慧树答案python程序设计_2020年智慧树Python程序设计答案章节期末答案
  7. 退役旧数据节点-黑名单退役
  8. 【PyG学习入门】一:入门使用
  9. IaaS:基础设施及服务
  10. KiCad设计PCB-1-元器件库的制作(1)