一、說明
Vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成, 讓構(gòu)建單頁面應(yīng)用變得易如反掌。包含的功能有:
- 嵌套的路由/視圖表
- 模塊化的、基于組件的路由配置
- 路由參數(shù)、查詢、通配符
- 基于Vue js過渡系統(tǒng)的視圖過渡效果
- 細粒度的導(dǎo)航控制
- 帶有自動激活的CSS class的鏈接
- HTML5 歷史模式或hash模式, 在IE 9中自動降級
- 自定義的滾動行為
二、安裝
基于第一個vue-cli進行測試學(xué)習(xí); 先查看node modules中是否存在vue-router
vue-router是一個插件包, 所以我們還是需要用npm/cnpm來進行安裝的。打開命令行工具,進入你的項目目錄,輸入下面命令。
1
|
npm install vue-router --save-dev |
如果在一個模塊化工程中使用它,必須要通過Vue.use()明確地安裝路由功能:
1
2
3
4
|
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter); |
三、測試
1、先刪除沒有用的東西
2、components 目錄下存放我們自己編寫的組件
3、定義一個Content.vue 的組件
1
2
3
4
5
6
7
8
9
10
11
|
< template > < div > < h1 >內(nèi)容頁</ h1 > </ div > </ template > < script > export default { name:"Content" } </ script > |
Main.vue組件
1
2
3
4
5
6
7
8
9
10
11
|
< template > < div > < h1 >首頁</ h1 > </ div > </ template > < script > export default { name:"Main" } </ script > |
4、安裝路由,在src目錄下,新建一個文件夾: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
26
27
28
29
|
import Vue from 'vue' //導(dǎo)入路由插件 import Router from 'vue-router' //導(dǎo)入上面定義的組件 import Content from '../components/Content' import Main from '../components/Main' //安裝路由 Vue.use(Router) ; //配置路由 export default new Router({ routes:[ { //路由路徑 path: '/content' , //路由名稱 name: 'content' , //跳轉(zhuǎn)到組件 component:Content }, { //路由路徑 path: '/main' , //路由名稱 name: 'main' , //跳轉(zhuǎn)到組件 component:Main } ] }); |
5、在main.js中配置路由
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import Vue from 'vue' import App from './App' //導(dǎo)入上面創(chuàng)建的路由配置目錄 import router from './router' //自動掃描里面的路由配置 //來關(guān)閉生產(chǎn)模式下給出的提示 Vue.config.productionTip = false ; new Vue({ el: "#app" , //配置路由 router, components:{App}, template: '<App/>' }); |
6、在App.vue中使用路由
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< template > < div id = "app" > <!-- router-link:默認會被渲染成一個<a>標簽,to屬性為指定鏈接 router-view:用于渲染路由匹配到的組件 --> < router-link to = "/main" >首頁</ router-link > < router-link to = "/content" >內(nèi)容</ router-link > < router-view ></ router-view > </ div > </ template > < script > export default{ name:'App' } </ script > < style ></ style > |
以上就是Vue-router路由該如何使用的詳細內(nèi)容,更多關(guān)于Vue-router路由使用的資料請關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://www.cnblogs.com/cjzlh/p/14457881.html