路由中有三个基本的概念 route, routes, router。
1. route: 是一条路由,它是单数, Home按钮 => home内容, 这是一条route, about按钮 => about 内容, 这是另一条路由。
2. routes: 是一组路由,把上面的每一条路由组合起来,形成一个数组。[{home 按钮 =>home内容 }, { about按钮 => about 内容}]
3. router: 是一个机制,相当于一个管理者,它来管理路由。因为routes 只是定义了一组路由,它放在哪里是静止的,当真正来了请求,怎么办? 就是当用户点击home 按钮的时候,怎么办?这时router 就起作用了,它到routes 中去查找,去找到对应的 home 内容,所以页面中就显示了 home 内容。
vue-router 中的路由也是基于上面的三个基本概念来实现的,我们只要把路径和组件对应起来,然后在页面中把组件渲染出来
1.页面实现
在vue-router中有两个标签
2.js中配置
定义route,是一个对象有两部分组成:path 和 component 。path指路径,component指组件。比如:
{ path: '/home', component: login }
两条路由就组成一个routes:
const routes = [
{ path: '/home', component: home },
{ path: '/about', component: about }
]
最后创建router对路由进行管理,由构造函数new vueRouter()创建,接受routes参数。
const router = new vueRouter({
routes: [
{ path: '/home', component: home },
{ path: '/about', component: about }
]
})
配置完成后,把router注入到vue根实例中(main.js)
new Vue({
router
})
现在使用一下
1.建立home.vue 和 about.vue
// home.vue
home
{{homeMsg}}
// about.vue
about
{{aboutMsg}}
2.在App.vue中 定义
Home
About
3.在router下的index.js中定义router
import Vue from 'vue'
import Router from 'vue-router'
import home from '../home.vue';
import about from "../about.vue";
Vue.use(Router)
export default new Router({
routes: [
{
path: "/home",
name: "home",
component: home,
},
{
path: "/about",
name: "about",
component: about
}
]
})
这时候有个问题,当进入页面时没有任何内容,点击后才有内容。因为首次进入页面,它的路径是"/",没有给这个路径做相应的配置。所以要用到重定向。所谓重定向,就是重新给它指定一个方向。
// 重定向
{
path: '/',
redirect: '/home'
}
/* 选中的样式 */
a.router-link-active {
color: red;
}
/* 未选中的样式 */
.gray {
color: gray
}