路由的封装抽离:在src目录下新建router文件夹,router文件下新建index.js文件,在里面配置路由。好处:拆分模块,利于维护。
一、5个基本步骤
1.下载:下载VueRouter模块到当前工程。命令:npm i vue-router@3
2.引入:
import Vue from 'vue'
import VueRouter from 'vue-router'
3.安装注册:Vue.use(VueRouter)
4.创建路由对象:const router = new VueRouter( )
5.注入:将路由对象注入到new Vue实例中,建立关联。
new Vue({
render: h => h(App),
router
}).$mount('#app')
二、2个核心步骤
1.创建需要的组件(views目录),配置路由规则(路径和组件的匹配关系)。
2.配置导航,配置路由出口 router-view (路径对应的组件显示的位置)
router 下的index.js如下
// @/views 绝对路径 : 基于 @ 指代 src 目录,从 src 目录出发找组件
import Find from '@/views/Find'
import My from '@/views/My'
import Friend from '@/views/Friend'import Vue from 'vue'
import VueRouter from 'vue-router'//VueRouter插件初始化
Vue.use(VueRouter)//创建路由对象
const router = new VueRouter({//路由规则们,数组包对象。一条路由规则{path:路径,component:组件}routes: [{ path: '/find', component: Find },{ path: '/my', component: My },{ path: '/friend', component: Friend }],//自定义类名linkActiveClass: 'active', //配置模糊匹配的类名linkExactActiveClass: 'exact-active' //配置精确匹配的类名
})export default router
App.vue如下(简单介绍 router-link )
<template><div><div class="footer_wrap"><!-- 1.router-link是什么?vue-router提供的全局组件,用于替换a标签2.router-link怎么用?<router-link to="/路径值"></router-link>必须传入to属性,指定路由路径值3.router-link好处?能跳转,能高亮(自带激活时的类名) --><router-link to="/find">发现音乐</router-link><router-link to="/my">我的音乐</router-link><router-link to="/friend">朋友</router-link></div><div class="top"><!-- 路由出口(所匹配的组件展示的位置) --><router-view></router-view></div></div>
</template><script>
export default {};
</script><style>
/* router-link 会自动给当前导航添加两个类名 区别 */
/* 1. router-link-active 模糊匹配(用的多) to='/find => 地址栏/find /find/one /find/two *//* 2. router-link-exact-active 精确匹配 to='/find => 地址栏/find */
.footer_wrap a.active {background-color: red;
}body {margin: 0;padding: 0;
}
.footer_wrap {position: relative;left: 0;top: 0;display: flex;width: 100%;text-align: center;background-color: #333;color: #ccc;
}
.footer_wrap a {flex: 1;text-decoration: none;padding: 20px 0;line-height: 20px;background-color: #333;color: #ccc;border: 1px solid black;
}
.footer_wrap a:hover {background-color: #555;
}</style>