一.路由
1.定义
node中的路由:web服务器根据用户输入的不同url地址,来返回不同的页面.
vue中路由:路由是vue.js中的一个路由组件,需要结合组件来实现单页面应用.
2.路由的使用(一级路由)
2-1.安装项目
vue init webpack 项目名称
npm run dev
2-2.清空工作
assest: logo.png删除
components: helloWord.vue 删除
App.vue : 内容清空
main.js
2-3.新建三个组件
新建login.vue home.vue about.vue
2-4.路由安装及引入
官网:https://router.vuejs.org/zh/
1.安装下载: cnpm i vue-router --save
2.main.js引入:
// 引入路由
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
2-5.引入组件
main.js
// 导出组件
import login from './components/login'
import home from './components/home'
import about from './components/about'
2-6.配置组件路由规则
// 配置路由组件规则
const router = new Router({
// routes规则
routes:[
{
path:'/login',
component:login
},
{
path:'/home',
component:home
},
{
path:'/about',
component:about
}
]
})
2-7.将router实例放在vue实例
new Vue({
el: '#app',
components: { App },
template: '<App/>',
router,//将路由选项放在vue实例上
})
2-8.路由出口
App.vue
<template>
<div>
<!-- 路由出口 -->
<router-view></router-view>
</div>
</template>
2-9.访问
在浏览器中访问:
http://localhost:8080/#/about
http://localhost:8080/#/login
http://localhost:8080/#/home
2-10.路由组件之间跳转
<router-link to="/login">登录</router-link> |
<router-link to="/about">关于我们</router-link>
2-11.重定向
{
path:'*',//*:任何不存在路由
redirect:'/login',//redirect:重定向
}
3.二级路由
3-1.新建三个组件
新建man.vue women.vue child.vue
3-2.引入组件
main.js
import man from './components/man'
import women from './components/women'
import child from './components/child'
3-3.配置二级路由规则
{
path:'/home',
component:home,
children:[
{
path:'man',
component:man
},
{
path:'women',
component:women
},
{
path:'child',
component:child
},
}
3-4.二级路由出口
<!-- 二级路由出口 -->
<router-view></router-view>
4.选中样式
<style scoped>
/* 方式一:使用系统默认的类名 */
/* .router-link-exact-active{
background: greenyellow;
color: white;
} */
/* 方式二:active-class选中的样式 */
.select{
background: hotpink;
color:greenyellow;
}
</style>
5.路由的优化
src
router
index.js
// 1.引入路由
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
// 2.导出组件
import login from '../components/login'
import home from '../components/home'
import about from '../components/about'
import man from '../components/man'
import women from '../components/women'
import child from '../components/child'
// 3配置路由组件规则
const router = new Router({
// routes规则
routes:[
{
path:'/login',
component:login
},
{
path:'/home',
component:home,
children:[
{
path:'man',
component:man
},
{
path:'women',
component:women
},
{
path:'child',
component:child
},
{
path:'',
redirect:'/home/women'
}
]
},
{
path:'/about',
component:about
},
{
path:'*',//*:任何不存在路由
redirect:'/login',//redirect:重定向
}
]
})
export default router