Vue is one of the most popular front-end frameworks currently. It is not only simple and easy to use, but also has strong scalability. One of the plug-ins worth paying attention to is vue-router. vue-router is the official routing plug-in for Vue. It can better control routing navigation in Vue applications, make the relationship between routing and components clearer, and improve the user's interactive experience. This article will explain in detail how to use Vue-router and its wonderful uses.
1. Installation and use
Before using vue-router, you need to install it first. You can use the npm package manager to install the vue-router plugin. The installation command is as follows:
npm install vue-router
After the installation is completed, introduce and use vue-router in the main.js file:
import VueRouter from 'vue-router' import routes from './router' const router = new VueRouter({ routes }) new Vue({ el: '#app', router, render: h => h(App) })
Among them, the routes parameter specifies the routing configuration, which can be modified according to project needs. Then pass in the router parameter in the Vue instantiation object to enable the routing function.
2. Basic configuration
Routing configuration consists of two parts: routing table and routing component. The routing table is mainly used to configure routing paths and corresponding components. The routing component is the component view of the corresponding routing path.
Create the router.js file in the src directory to define the routing table and components. As follows:
import Home from './views/Home.vue' import About from './views/About.vue' export default [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: About } ]
Then introduce the routing configuration in main.js and pass it into the VueRouter instance. Among them, the routing path is configured using the path attribute, and the component attribute specifies the corresponding routing component.
3. Parameter passing
Vue-router also supports passing parameters, and the passed parameters can be obtained through the $route object.
Path passing parameters refers to placing parameters as part of the routing path, for example:
{ path: '/user/:userId', name: 'user', component: User }
When the user accesses /user/ When 1, the route will pass 1 as the parameter userId to the User component.
Query parameter passing means placing the parameters after the routing path in the form of key-value pairs, separated by question marks?, consecutive keys Value pairs are connected with &, for example:
{ path: '/user', name: 'user', component: User }
When the user accesses /user?id=1&name=john, the route will pass {id: 1, name: 'john'} as query parameters to the User component.
4. Redirection and nested routing
Redirection refers to when the user accesses a certain path in the browser, Automatically jump to another path. The following code implements the function of automatically jumping from the path /about to the path /home:
import Home from './views/Home.vue' import About from './views/About.vue' export default [ { path: '/', redirect: '/home' }, { path: '/home', name: 'home', component: Home }, { path: '/about', redirect: '/home' } ]
Nested routing refers to using the child in the parent component Component routing. For example, in a page with a fixed structure at the head and bottom, the "content" component needs to be nested. The three-layer structure looks like this:
header / L R | content | footer
Nested routing requires the use of
const home = { template: ` <div> <h2>Home</h2> <router-view></router-view> </div> ` } const about = { template: '<div>About</div>' } const contact = { template: '<div>Contact</div>' } const router = new VueRouter({ routes: [ { path: '/', name: 'home', component: home, children: [ { path: 'about', name: 'about', component: about }, { path: 'contact', name: 'contact', component: contact } ] } ] })
The
5. Routing Guard
Global guard will be triggered before routing switching, among which beforeEach() is the global pre-guard, which can be Perform operations such as permission verification and login verification.
router.beforeEach((to, from, next) => { // 验证用户是否登陆 if(to.path === '/login') { next(); } else { let token = localStorage.getItem('token'); if(token === null || token === '') { next('/login'); } else { next(); } } })
The global post guard is used to trigger after routing switching and is used to handle operations such as the progress bar of page loading.
Route exclusive guard is used to make specific processing for a certain route. Just add the beforeEnter attribute definition in the route configuration.
const router = new VueRouter({ routes: [ { path: '/admin', name: 'admin', component: admin, beforeEnter: (to, from, next) => { // 验证是否为管理员账户 let token = localStorage.getItem('token'); if(token === 'admin') { next(); } else { next('/'); } } } ] })
In-component guards are mainly used to process the current component. Including: three guard functions: beforeRouteEnter, beforeRouteUpdate and beforeRouteLeave.
The beforeRouteEnter function is triggered before the component enters. The component instance cannot be directly accessed in this function, but the component instance can be passed through the next callback function for processing.
export default { data () { return { user: {} } }, beforeRouteEnter (to, from, next) { axios.get(`/api/user/${to.params.id}`).then(response => { next(vm => vm.setUser(response.data.user)) }) }, methods: { setUser (user) { this.user = user } } }
beforeRouteUpdate function Since routing jumps between components will not recreate instances, you need to use the beforeRouteUpdate function for processing.
export default { watch: { '$route' (to, from) { // 对路由变化作出响应... } }, beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() } }
The beforeRouteLeave function is triggered when the component is about to be left and is used to handle operations such as unsaved form data.
export default { beforeRouteLeave (to, from, next) { // 如果表单已保存或者页面没有修改,直接离开该页面 if (this.saved || window.confirm('尚未保存,确定要离开吗?')) { next() } else { next(false) } } }
6. Summary
Using the vue-router plug-in can provide powerful control capabilities for routing navigation in Vue applications, thereby improving the user's interactive experience. This article introduces the basic configuration, parameter passing, redirection, nested routing and routing guards of vue-router, which can help developers better use the vue-router plug-in.
The above is the detailed content of Detailed explanation of the wonderful use of vue-router in Vue. For more information, please follow other related articles on the PHP Chinese website!