11.vue-router路由

1.什么是vue-router路由

  Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

2.安装

  基于一个创建好的Vue项目,在终端输入

npm install vue-router --save-dev

3.使用

  1. 删除项目中不需要的内容

  2. 在components目录下编写自己的组件:Content.vue,Main.vue

  3. 安装路由,在src目录下,新建router文件夹用于存放路由,router文件夹中建立index.js用于配置管理所有路由

  4. 在项目下的main.js获得和配置路由

  5. 在App.vue中使用路由

项目整体架构:

1.编写自己的组件

Content.vue:

 1 <template>
 2     <h1>内容页</h1>
 3 </template>
 4 
 5 <script>
 6     export default {
 7         name: "Content"
 8     }
 9 </script>
10 
11 <style scoped>
12 
13 </style>

Main.vue:

 1 <template>
 2     <h1>首页</h1>
 3 </template>
 4 
 5 <script>
 6     export default {
 7         name: "Main"
 8     }
 9 </script>
10 
11 <style scoped>
12 
13 </style>

2.配置管理自己的组件

index.js:

 1 import Vue from 'vue'
 2 import VueRouter from 'vue-router'
 3 
 4 import Content from '../components/Content'
 5 import Main from '../components/Main'
 6 
 7 //安装路由
 8 Vue.use(VueRouter)
 9 
10 //配置导出路由
11 
12 export default new VueRouter({
13   routes: [
14     {
15       //路由路径
16       path: '/content',
17       name: 'content',
18       //跳转的组件
19       component: Content
20     },
21     {
22       //路由路径
23       path: '/main',
24       name: 'main',
25       //跳转的组件
26       component: Main
27     }
28     
29   ]
30 })

3.获取路由

main.js:

 1 import Vue from 'vue'
 2 import App from './App'
 3 
 4 import router from './router'   //自动扫描里面的路由配置,获取路由
 5 
 6 Vue.config.productionTip = false
 7 
 8 
 9 new Vue({
10   el: '#app',
11   //配置路由
12   router,
13   components: { App },
14   template: '<App/>'
15 })

4.配置路由

App.vue:

 1 <template>
 2   <div id="app">
 3     <h1>Vue-Router</h1>
 4     <router-link to="/main">首页</router-link>
 5     <router-link to="/content">内容页</router-link>
 6     <router-view></router-view>
 7   </div>
 8 </template>
 9 
10 <script>
11 
12 
13 
14 export default {
15   name: 'App',
16 }
17 </script>
18 
19 <style>
20 #app {
21   font-family: 'Avenir', Helvetica, Arial, sans-serif;
22   -webkit-font-smoothing: antialiased;
23   -moz-osx-font-smoothing: grayscale;
24   text-align: center;
25   color: #2c3e50;
26   margin-top: 60px;
27 }
28 </style>

5.启动展示

npm run dev

 

posted @ 2019-12-23 01:01  All_just_for_fun  阅读(1112)  评论(0编辑  收藏  举报