This time I will bring you a detailed explanation of the use of Vue-router's routingmetainformation. What are the notesfor using Vue-router's routing metainformation? The following is a practical case. Get up and take a look.
1. Background
In the past, when writing the front-end, I used the back-end return interface. You don’t have to worry about jumping to Shenma. But this time I used vue. The front-end I wrote was the first time the front-end and back-end were separated. The back-end only provided a data interface to the front-end. At first, I thought it was the back-end control interface that was used to render Shenma, but after thinking about it later, the routing and Shenma were all controlled by the front-end. , I couldn’t reach the back end, so I kept wandering around. On the official website of vue-router, I thought there should be something related, and then I found the routing meta information. I didn’t understand what it meant at first, but later I figured it out and recorded it
2. Code analysis
Official website routing meta information
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, meta: { requiresAuth: true }// a meta field } ] })
The meta field here is the routing meta information field, and requiresAuth is the field name I created to mark whether this routing information needs to be detected, true It means that it needs to be tested, false means that it does not need to be tested (the name can be chosen casually, for example, my own requiresId, or if you are too lazy to think about it, just a, b Starting from this, of course, it is more recommended to give a meaningful name)
(2) js code
new Vue({ el: '#app', router, template: '<App/>', components: { App }, render: h => h(App), created () { this.redrct() }, methods: { redrct () { router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresId)) { //这里meta字段的名称要与上面route里面保持一致 // this route requires Id, check if logged in // if not, redirect to login page. if (!this.loggedIn()) { // 自己的判断条件 next({ path: '/', // 重定向后的路由 query: { redirect: to.fullPath } // 登录成功之后可以根据query中的内容跳转回原来的路由(页面) }) } else { next() } } else { next() // 确保一定要调用 next() } }) }, loggedIn () { var id = sessionStorage.getItem('userId') if (id === null) { // 未登录 return false } return true // 别忘了这句啊,之前忘写了,调了好半天呢 } } })
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use the Particles.js library in vue
Detailed explanation of the use of Three.js
The above is the detailed content of Detailed explanation of the use of routing metainformation of Vue-router. For more information, please follow other related articles on the PHP Chinese website!