小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
前文我们简单学习了前端路由 hash 模式解析, 今天继续学习Vue配套路由 Vue-Router 的使用及路由的重定向和 404页面该如何做
路由重定向
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。
用
Vue.js + Vue Router创建单页应用,是非常简单的。使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 Vue Router 添加进来,我们需要做的是,将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。
// App.vue
<template>
<div id="app">
<!-- <router-link :to="'/'+type">pages</router-link> -->
<router-link to="/page-one">page-one</router-link>
<router-link to="/page-two">page-two</router-link>
<router-link to="/page-three">page-three</router-link>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
// src/router/index.js 路由定义模块 -- 路由重定向 redirect
import Vue from 'vue'
import Router from 'vue-router'
import One from '@/components/One'
import Two from '@/components/Two'
import Three from '@/components/Three'
import NotFound from '@/components/NotFound'
Vue.use(Router)
export default new Router({
mode:"history",
// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
routes: [
{
path:"/",
redirect:{name:"One"} // 重定向到name为 One 的路由
},
{
path:"/page-one",
name:"One",
component: One
},
{
path:"/page-two",
name:"Two",
component: Two
},
{
path: "/page-three",
component: Three
},
{
path: "**",
component: NotFound // 404页面该如何做, 找不到页面定义到notfound404页面
}
]
})
router-link-active
设置 链接激活时使用的 CSS 类名
.router-link-active {
color: red;
}
router-link-exact-active
精确匹配 到才会生效.