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
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
包含原始目标路线对象,并带有诸如路线的path
或name
。
别名 (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 路由重定向