vue路由登录拦截器

介绍 (Introduction)

In a JavaScript web application, a router is the part that syncs the currently displayed view with the browser address bar content.

在JavaScript Web应用程序中,路由器是将当前显示的视图与浏览器地址栏内容同步的部分。

In other words, it’s the part that makes the URL change when you click something in the page, and helps to show the correct view when you hit a specific URL.

换句话说,这是当您单击页面中的某些内容时更改URL的部分,并有助于在您单击特定的URL时显示正确的视图。

Traditionally the Web is built around URLs. When you hit a certain URL, a specific page is displayed.

传统上,Web是围绕URL构建的。 当您点击某个URL时,将显示一个特定页面。

With the introduction of applications that run inside the browser and change what the user sees, many applications broke this interaction, and you had to manually update the URL with the browser’s History API.

随着在浏览器中运行的应用程序的引入并改变用户的外观,许多应用程序中断了这种交互,因此您必须使用浏览器的History API手动更新URL。

You need a router when you need to sync URLs to views in your app. It’s a very common need, and all the major modern frameworks now allow you to manage routing.

当您需要将URL同步到应用程序中的视图时,需要一个路由器。 这是一个非常普遍的需求,现在所有主要的现代框架都允许您管理路由。

The Vue Router library is the way to go for Vue.js applications. Vue does not enforce the use of this library. You can use whatever generic routing library you want, or also create your own History API integration, but the benefit of using Vue Router is that it’s official.

Vue路由器库是用于Vue.js应用程序的方式。 Vue不强制使用此库。 您可以使用任何所需的通用路由库,也可以创建自己的History API集成,但是使用Vue Router的好处是它是官方的

This means it’s maintained by the same people who maintain Vue, so you get a more consistent integration in the framework, and the guarantee that it’s always going to be compatible in the future, no matter what.

这意味着它由维护Vue的同一个人维护,因此您将在框架中获得更一致的集成,并保证无论将来如何,它始终是兼容的。

安装 (Installation)

Vue Router is available via npm with the package named vue-router.

Vue Router可通过npm与名为vue-router的软件包一起使用。

If you use Vue via a script tag, you can include Vue Router using

如果通过脚本标签使用Vue,则可以使用

<script src="https://unpkg.com/vue-router"></script>

unpkg.com is a very handy tool that makes every npm package available in the browser with a simple link

unpkg.com是一个非常方便的工具,通过简单的链接即可在浏览器中使用每个npm软件包。

If you use the Vue CLI, install it using

如果您使用Vue CLI ,请使用

npm install vue-router

Once you install vue-router and make it available either using a script tag or via Vue CLI, you can now import it in your app.

安装vue-router并使用脚本标签或通过Vue CLI使它可用后,现在可以将其导入应用程序中。

You import it after vue, and you call Vue.use(VueRouter) to install it inside the app:

您将其导入到vue之后,然后调用Vue.use(VueRouter)将其安装在应用程序中:

import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter)

After you call Vue.use() passing the router object, in any component of the app you have access to these objects:

在通过路由器对象调用Vue.use()之后,在应用程序的任何组件中您都可以访问以下对象:

  • this.$router is the router object

    this.$router是路由器对象

  • this.$route is the current route object

    this.$route是当前的路由对象

路由器对象 (The router object)

The router object, accessed using this.$router from any component when the Vue Router is installed in the root Vue component, offers many nice features.

在根Vue组件中安装Vue路由器后,可使用this.$router从任何组件访问该路由器对象,这些对象具有许多不错的功能。

We can make the app navigate to a new route using

我们可以使用以下方法使应用导航到新路线

  • this.$router.push()

    this.$router.push()

  • this.$router.replace()

    this.$router.replace()

  • this.$router.go()

    this.$router.go()

which resemble the pushState, replaceState and go methods of the History API.

类似于History API的pushStatereplaceStatego方法。

push() is used to go to a new route, adding a new item to the browser history. replace() is the same, except it does not push a new state to the history.

push()用于转到新路线,将新项目添加到浏览器历史记录中。 replace()相同,只是它不会将新状态推入历史记录。

Usage samples:

用法样本:

this.$router.push('about') //named route, see later
this.$router.push({ path: 'about' })
this.$router.push({ path: 'post', query: { post_slug: 'hello-world' } }) //using query parameters (post?post_slug=hello-world)
this.$router.replace({ path: 'about' })

go() goes back and forth, accepting a number that can be positive or negative to go back in the history:

go()来回移动,接受可以在历史记录中返回的正数或负数:

this.$router.go(-1) //go back 1 step
this.$router.go(1) //go forward 1 step

定义路线 (Defining the routes)

I’m using a Vue Single File Component in this example.

在此示例中,我使用的是Vue单个文件组件 。

In the template I use a nav tag that has 3 router-link components, which have a label (Home/Login/About) and a URL assigned through the to attribute.

在模板中,我使用了一个nav标签,该标签包含3个router-link组件,这些组件具有标签(Home / Login / About)和通过to属性分配的URL。

The router-view component is where the Vue Router will put the content that matches the current URL.

router-view组件是Vue路由器将放置与当前URL匹配的内容的位置。

<template><div id="app"><nav><router-link to="/">Home</router-link><router-link to="/login">Login</router-link><router-link to="/about">About</router-link></nav><router-view></router-view></div>
</template>

A router-link component renders an a tag by default (you can change that). Every time the route changes, either by clicking a link or by changing the URL, a router-link-active class is added to the element that refers to the active route, allowing you to style it.

默认情况下, router-link组件会呈现a标记(您可以更改它)。 每当通过单击链接或更改URL来更改router-link-active ,都会将router-link-active类添加到引用活动路由的元素中,以设置其样式。

In the JavaScript part we first include and install the router, then we define 3 route components.

在JavaScript部分中,我们首先包括并安装路由器,然后定义3个路由组件

We pass them to the initialization of the router object, and we pass this object to the Vue root instance.

我们将它们传递给router对象的初始化,然后将此对象传递给Vue根实例。

Here’s the code:

这是代码:

<script>
import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter)const Home  = {template: '<div>Home</div>'
}const Login = {template: '<div>Login</div>'
}const About = {template: '<div>About</div>'
}const router = new VueRouter({routes: [{ path: '/', component: Home },{ path: '/login', component: Login },{ path: '/about', component: About }]
})new Vue({router
}).$mount('#app')
</script>

Usually, in a Vue app you instantiate and mount the root app using:

通常,在Vue应用程序中,您可以使用以下方法实例化并挂载根应用程序:

new Vue({render: h => h(App)
}).$mount('#app')

When using the Vue Router, you don’t pass a render property but instead, you use router.

使用Vue Router时,您不传递render属性,而是使用router

The syntax used in the above example:

上例中使用的语法:

new Vue({router
}).$mount('#app')

is a shorthand for

是的简写

new Vue({router: router
}).$mount('#app')

See in the example, we pass a routes array to the VueRouter constructor. Each route in this array has a path and component params.

在示例中看到,我们将一个routes数组传递给VueRouter构造函数。 此数组中的每个路由都有一个pathcomponent参数。

If you pass a name param too, you have a named route.

如果您也传递了name参数,那么您将拥有一个命名路线

使用命名路由将参数传递到路由器的推入和替换方法 (Using named routes to pass parameters to the router push and replace methods)

Remember how we used the Router object to push a new state before?

还记得我们以前如何使用Router对象推送新状态吗?

this.$router.push({ path: 'about' })

With a named route we can pass parameters to the new route:

使用命名的路由,我们可以将参数传递给新的路由:

this.$router.push({ name: 'post', params: { post_slug: 'hello-world' } })

the same goes for replace():

replace()也是一样:

this.$router.replace({ name: 'post', params: { post_slug: 'hello-world' } })

用户单击router-link时会发生什么 (What happens when a user clicks a router-link)

The application will render the route component that matches the URL passed to the link.

该应用程序将呈现与传递给链接的URL匹配的路由组件。

The new route component that handles the URL is instantiated and its guards called, and the old route component will be destroyed.

实例化处理URL的新路由组件,并调用其防护措施,旧的路由组件将被销毁。

路线守卫 (Route guards)

Since we mentioned guards, let’s introduce them.

既然我们提到过守卫 ,就让我们对其进行介绍。

You can think of them of life cycle hooks or middleware, those are functions called at specific times during the execution of the application. You can jump in and alter the execution of a route, redirecting or cancelling the request.

您可以将它们视为生命周期挂钩或中间件,它们是在应用程序执行期间的特定时间调用的函数。 您可以加入并更改路由的执行,重定向或取消请求。

You can have global guards by adding a callback to the beforeEach() and afterEach() property of the router.

您可以通过向路由器的beforeEach()afterEach()属性添加回调来获得全局保护。

  • beforeEach() is called before the navigation is confirmed

    在确认导航之前调用beforeEach()

  • beforeResolve() is called when beforeEach is executed and all the components beforeRouterEnter and beforeRouteUpdate guards are called, but before the navigation is confirmed. The final check, if you want

    在执行beforeRouterEnter并且beforeRouteUpdate所有组件beforeRouterEnterbeforeRouteUpdate保护之后,但在确认导航之前,调用beforeResolve beforeResolve() 。 最终检查(如果需要)

  • afterEach() is called after the navigation is confirmed

    确认导航后调用afterEach()

What does “the navigation is confirmed” mean? We’ll see it in a second. In the meantime think of it as “the app can go to that route”.

“导航已确认”是什么意思? 我们将在一秒钟内看到它。 同时,将其视为“应用程序可以走那条路”。

The usage is:

用法是:

this.$router.beforeEach((to, from, next) => {// ...
})

this.$router.afterEach((to, from) => {// ...
})

to and from represent the route objects that we go to and from. beforeEach has an additional parameter next which if we call with false as the parameter, will block the navigation, and cause it to be unconfirmed. Like in Node middleware, if you’re familiar, next() should always be called otherwise execution will get stuck.

to from表示我们from的路线对象。 beforeEach还有一个next一个参数,如果我们使用false作为参数进行调用,它将阻止导航并导致其不确定。 就像在Node中间件中一样,如果您很熟悉,则应始终调用next(),否则执行将卡住。

Single route components also have guards:

单路径组件还具有防护装置:

  • beforeRouteEnter(from, to, next) is called before the current route is confirmed

    在确认当前路由之前调用beforeRouteEnter(from, to, next)

  • beforeRouteUpdate(from, to, next) is called when the route changes but the component that manages it is still the same (with dynamic routing, see next)

    当路由更改但管理它的组件仍然相同时beforeRouteUpdate(from, to, next)调用beforeRouteUpdate(from, to, next) (使用动态路由,请参见下一个)

  • beforeRouteLeave(from, to, next) is called when we move away from here

    当我们离开这里时,将调用beforeRouteLeave(from, to, next)

We mentioned navigation. To determine if the navigation to a route is confirmed, Vue Router performs some checks:

我们提到了导航。 要确定是否确认导航到路由,Vue Router会执行一些检查:

  • it calls beforeRouteLeave guard in the current component(s)

    它在当前组件中调用beforeRouteLeave保护

  • it calls the router beforeEach() guard

    它在beforeEach()守护程序之前调用路由器

  • it calls the beforeRouteUpdate() in any component that needs to be reused, if any exist

    它会在需要重用的任何组件(如果存在beforeRouteUpdate()中调用beforeRouteUpdate()

  • it calls the beforeEnter() guard on the route object (I didn’t mention it but you can look here)

    它在路由对象上调用beforeEnter()保护(我没有提到它,但是您可以在这里查看 )

  • it calls the beforeRouterEnter() in the component that we should enter into

    它在我们应该输入的组件中调用beforeRouterEnter()

  • it calls the router beforeResolve() guard

    它调用路由器的beforeResolve()保护

  • if all was fine, the navigation is confirmed!如果一切正常,导航已确认!
  • it calls the router afterEach() guard

    它在afterEach()保护之后调用路由器

You can use the route-specific guards (beforeRouteEnter and beforeRouteUpdate in case of dynamic routing) as life cycle hooks, so you can start data fetching requests for example.

您可以使用特定于路由的防护(在动态路由的情况下,使用beforeRouteEnterbeforeRouteUpdate )作为生命周期挂钩,因此可以例如启动数据获取请求

动态路由 (Dynamic routing)

The example above shows a different view based on the URL, handling the /, /login and /about routes.

上面的示例显示了一个基于URL的不同视图,该视图处理//login/about路由。

A very common need is to handle dynamic routes, like having all posts under /post/, each with the slug name:

一个非常普遍的需求是处理动态路由,例如将所有帖子都放在/post/ ,每个/post/都带有一个名字。

  • /post/first

    /post/first

  • /post/another-post

    /post/another-post

  • /post/hello-world

    /post/hello-world

You can achieve this using a dynamic segment.

您可以使用动态细分来实现。

Those were static segments:

这些是静态段:

const router = new VueRouter({routes: [{ path: '/', component: Home },{ path: '/login', component: Login },{ path: '/about', component: About }]
})

we add in a dynamic segment to handle blog posts:

我们添加了一个动态细分来处理博客文章:

const router = new VueRouter({routes: [{ path: '/', component: Home },{ path: '/post/:post_slug', component: Post },{ path: '/login', component: Login },{ path: '/about', component: About }]
})

Notice the :post_slug syntax. This means that you can use any string, and that will be mapped to the post_slug placeholder.

注意:post_slug语法。 这意味着您可以使用任何字符串,并将其映射到post_slug占位符。

You’re not limited to this kind of syntax. Vue relies on this library to parse dynamic routes, and you can go wild with Regular Expressions.

您不仅限于这种语法。 Vue依赖于此库来解析动态路由,并且您可以使用正则表达式疯狂。

Now inside the Post route component we can reference the route using $route, and the post slug using $route.params.post_slug:

现在,在Post route组件内部,我们可以使用$route引用$route ,并使用$route.params.post_slug来引用slug:

const Post = {template: '<div>Post: {{ $route.params.post_slug }}</div>'
}

We can use this parameter to load the contents from the backend.

我们可以使用此参数从后端加载内容。

You can have as many dynamic segments as you want, in the same URL:

在同一URL中,可以有任意多个动态细分:

/post/:author/:post_slug

/post/:author/:post_slug

Remember when before we talked about what happens when a user navigates to a new route?

还记得我们之前谈到用户导航到新路线时会发生什么情况吗?

In the case of dynamic routes, what happens is a little different.

在动态路线的情况下,发生的情况有些不同。

Vue to be more efficient instead of destroying the current route component and re-instantiating it, it reuses the current instance.

Vue可以重用当前实例,而不是销毁当前路由组件并重新实例化,从而更加高效。

When this happens, Vue calls the beforeRouteUpdate life cycle event. There you can perform any operation you need:

发生这种情况时,Vue会调用beforeRouteUpdate生命周期事件。 在那里您可以执行所需的任何操作:

const Post = {template: '<div>Post: {{ $route.params.post_slug }}</div>'beforeRouteUpdate(to, from, next) {console.log(`Updating slug from ${from} to ${to}`)next() //make sure you always call next()}
}

使用道具 (Using props)

In the examples, I used $route.params.* to access the route data. A component should not be so tightly coupled with the router, and instead, we can use props:

在示例中,我使用$route.params.*访问路线数据。 组件不应与路由器紧密耦合,而可以使用道具:

const Post = {props: ['post_slug'],template: '<div>Post: {{ post_slug }}</div>'
}const router = new VueRouter({routes: [{ path: '/post/:post_slug', component: Post, props: true }]
})

Notice the props: true passed to the route object to enable this functionality.

注意props: true传递给route对象以启用此功能。

嵌套路线 (Nested routes)

Before I mentioned that you can have as many dynamic segments as you want, in the same URL, like:

在我提到之前,您可以在同一URL中具有任意数量的动态细分,例如:

/post/:author/:post_slug

/post/:author/:post_slug

So, say we have an Author component taking care of the first dynamic segment:

因此,假设我们有一个Author组件负责第一个动态段:

<template><div id="app"><router-view></router-view></div>
</template><script>
import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter)const Author  = {template: '<div>Author: {{ $route.params.author}}</div>'
}const router = new VueRouter({routes: [{ path: '/post/:author', component: Author }]
})new Vue({router
}).$mount('#app')
</script>

We can insert a second router-view component instance inside the Author template:

我们可以在Author模板中插入第二个router-view组件实例:

const Author  = {template: '<div>Author: {{ $route.params.author}}<router-view></router-view></div>'
}

we add the Post component:

我们添加了Post组件:

const Post = {template: '<div>Post: {{ $route.params.post_slug }}</div>'
}

and then we’ll inject the inner dynamic route in the VueRouter configuration:

然后将内部动态路由注入VueRouter配置中:

const router = new VueRouter({routes: [{path: '/post/:author',component: Author,children: [path: ':post_slug',component: Post]}]
})

翻译自: https://flaviocopes.com/vue-router/

vue路由登录拦截器

vue路由登录拦截器_Vue路由器相关推荐

  1. vue拦截器刷新登陆页面_Vue + Spring Boot 项目实战(六):前端路由与登录拦截器-Go语言中文社区...

    前言 这一篇主要讲前端路由与登录拦截器的实现.放在一起讲是因为我在开发登录拦截器时因为这个路由的问题遇到了很多坑,花费了很长时间,网上的解决方案都不怎么靠谱,综合了好几种办法才最终成功,其实关于这个部 ...

  2. Vue + Spring Boot 项目实战(七):前端路由与登录拦截器

    文章目录 前言 一.前端路由 二.使用 History 模式 三.后端登录拦截器 3.1. LoginController 3.2. LoginInterceptor 3.3. WebConfigur ...

  3. Vue + Spring Boot 项目实战(六):前端路由与登录拦截器

    本篇目录 前言 一.前端路由 二.使用 History 模式 三.后端登录拦截器 1.LoginController 2.LoginInterceptor 3.WebConfigurer 4.效果检验 ...

  4. Android登录拦截器实现方式(一)

    Android登录拦截器实现方式(一) 2015-08-04 22:12:01 标签:Android登录 拦截器 Interceptor 对于App端来说,如果能保证用户在登录后能自动延续登录前的操作 ...

  5. springboot整合shiro和session的详细过程和自定义登录拦截器

    文章目录 1.shiro依赖 2.shiro配置 shiro过滤器配置: 关联自定义的其他管理器 自定义会话工厂: 3.登陆时记录用户信息 4.shiro一些工具类的学习 5.自定义登录拦截器 shi ...

  6. Spring MVC 登录拦截器

    Spring MVC 登录拦截器 1.编写拦截器 package interceptor;import org.springframework.web.servlet.HandlerIntercept ...

  7. java 登录拦截器_springMVC 拦截器-用户登录拦截实战

    各位小伙伴 咱们继续学习新知识 今天要分享的就是 拦截器 不知道小伙伴们平时上网的时候有没有注意到,尤其是上网购物的时候,不登录账号,就无法访问一些功能页面,比如你不登录账号,就没法查看购物车里面有什 ...

  8. Spring Boot 实现登录拦截器,这才是正确的姿势!!

    原文:https://blog.csdn.net/qq_27198345/article/details/111401610 对于管理系统或其他需要用户登录的系统,登录验证都是必不可少的环节,在Spr ...

  9. Vue的axios拦截器

    Vue的axios拦截器 为什么要使用拦截器? ​ 在页面发送http请求,很多情况我们要对请求和其响应进行特定的处理,如:判断token,设置请求头.如果请求数非常多,单独对每一个请求进行处理会变得 ...

最新文章

  1. 找不到MSVCR100.DLL解决办法
  2. no need for pictures
  3. python3 生成器的send_Python:生成器中send()的行为
  4. ACM题目————一笔画问题
  5. python循环绘制六角星_《Python游戏趣味编程》 第3章 美丽的圆圈画
  6. (五)使用生成对抗网络 (GAN)生成新的时装设计
  7. Java8新特性学习_001_(Lambda表达式,函数式接口,方法引用,Stream类,Optional类)
  8. Python升级后pip命令失效解决方法
  9. 组态王曲线控件读取access_组态王,历史趋势曲线控件例程说明文档
  10. 20200527每日一句
  11. C语言程序设计实践-C语言应用实践
  12. adobe animate2022动画制作软件
  13. 英特尔cpu发布时间表_英特尔10代桌面cpu上市时间(英特尔10代发售时间)
  14. 怎样配置 Docker IPv6 ?
  15. 汤姆猫代码python_IOS 汤姆猫核心代码
  16. 一份还热乎的蚂蚁金服面经(已拿Offer)!附答案!!
  17. python类的封装是什么意思_python类封装 python中将函数和变量封装成类的好处
  18. HTML5作业:美食网站设计(浮动的使用)
  19. 手机内核是什么要怎么刷,小白必看的手机内核刷机命令
  20. 程序员成长之路(一)

热门文章

  1. 浅谈CRM系统:优化企业管理,提高客户满意度!
  2. 7000多万QQ群数据遭泄露 腾讯:确有其事已经修复
  3. html怎样把图片放进画布中,HTML5 canvas操作图片
  4. 【Blog】CSDN博客总排行榜
  5. 2011年-过年看的书
  6. PAT1027 打印沙漏(C++实现)
  7. 2012年下半年11月份系统架构设计师上午试题答案之一
  8. K12405 身份证号码
  9. win10安装miniconda3+pytorch1.2.0+cuda9.2+cudnn7.6.5.32
  10. 更换backbone心得