vue Router路由组件是vue的核心组件;
平时我们通过路由组件来实现导航菜单以及各种页面切换;
vue Router路由组件安装;
我们用vue-cli初始化的时候,可以选择添加vue Router;
也可以单独 执行 npm install vue-router --save 来安装;
我们首先建两个目录 router和pages,分别放路由路由模块配置文件和组件文件
再建两个组件Index.vue和Menu1.vue;
Index.vue
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<template> <div> Index首页 </div> </template> <script> export default { name: "Index" } </script> <style scoped> </style>
Menu1.vue
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<template> <div> 菜单一 </div> </template> <script> export default { name: "Menu1" } </script> <style scoped> </style>
router下建个路由配置文件index.js
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25/* 路由器模块 */ import Vue from 'vue' import VueRouter from 'vue-router' import Index from '../pages/Index' import Menu1 from '../pages/Menu1' Vue.use(VueRouter) export default new VueRouter({ // 多个路由 routes:[ { path:'/index', component:Index }, { path:'/menu1', component:Menu1 } ] })
main.js
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15/* 入口js:创建Vue实例 */ import Vue from 'vue' import App from './App' import router from './router' new Vue({ el:'#app', components:{ App }, template:'<App/>', router })
App.vue里:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44<template> <div> <div class="menu"> <ul> <li> <!--<a href="">首页</a>--> <router-link to="/index">首页</router-link> </li> <li> <!--<a href="">菜单1</a>--> <router-link to="/menu1">菜单1</router-link> </li> </ul> </div> <div class="content"> <router-view></router-view> </div> </div> </template> <script> export default { name: 'App', } </script> <style scoped> ul li{ float:left; padding-left: 20px; list-style-type: none; } ul li a{ text-decoration: none; } .content{ clear: both; padding: 20px; } </style>
router-link 里配置请求路由,通过路由配置,找到响应组件;
router-view里显示组件内容;
不过两个问题,没有默认显示页面页面;
我们配置下路由,默认显示下首页内容;
index.js修改下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30/* 路由器模块 */ import Vue from 'vue' import VueRouter from 'vue-router' import Index from '../pages/Index' import Menu1 from '../pages/Menu1' Vue.use(VueRouter) export default new VueRouter({ // 多个路由 routes:[ { path:'/index', component:Index }, { path:'/menu1', component:Menu1 }, { //默认访问 path:'/', redirect:'/index' } ] })
这样的话 默认首页 就会跳转到index请求;
还有一个,我们加个需求,点击的菜单,显示红色;
我们看下
选中的时候多了两个样式 router-link-exact-active router-link-active
我们可以给router-link-active 这个动态样式 加个color:red属性即可;
直接index.html里加:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>vue_demo</title> <style> /* 菜单颜色*/ .router-link-active{ color: red; } </style> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html>
效果:
最后
以上就是结实紫菜最近收集整理的关于23.Vue Router路由基本使用的全部内容,更多相关23.Vue内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复