前端路由就是URL中的hash与组件之间的对应关系。Vue Router
是Vue的官方路由。
组成:
VueRouter
:路由器类,根据路由请求在路由视图中动态渲染选中的组件。<router-link>
:请求链接组件,浏览器会解析成<a>
。<router-view>
:动态视图组件,用来渲染展示与路由路径对应的组件。
在组件中,使用 vue-router 提供的 <router-link>
和 <router-view>
声明路由链接和占位符:
组件:
<template><div><h1>Element</h1><router-link to="/one">One</router-link> <br><router-link to="/two">Two</router-link></div>
</template><script>export default {data() {return {}}
}
</script>
router/index.js
:
import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter)const routes = [{path: '/',name:'home',component: () => import('../views/router_lab/DefaultView.vue')},{path: '/one',name: 'one',component: () => import('../views/router_lab/OneView.vue')},{path: '/two',name: 'about',// route level code-splitting// this generates a separate chunk (about.[hash].js) for this route// which is lazy-loaded when the route is visited.component: () => import(/* webpackChunkName: "about" */ '../views/router_lab/TwoView.vue')}
]const router = new VueRouter({routes
})export default router
页面初始:
点击One
:
点击Two
:
路由重定向指的是:用户在访问地址 A
的时候,强制用户跳转
到地址 C ,从而展示特定的组件页面。通过路由规则的redirect
属性,指定一个新的路由地址,可以很方便地设置路由的重定向:
const routes = [{path: '/router_lab',name:'router_lab',redirect: '/one',},{path: '/',name:'home',component: () => import('../views/router_lab/DefaultView.vue')},{path: '/one',name: 'one',component: () => import('../views/router_lab/OneView.vue')},