Vue-router路由該如何使用
阿新 • • 發佈:2021-03-06
一、說明
vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度整合, 讓構建單頁面應用變得易如反掌。包含的功能有:
- 巢狀的路由/視圖表
- 模組化的、基於元件的路由配置
- 路由引數、查詢、萬用字元
- 基於Vue js過渡系統的檢視過渡效果
- 細粒度的導航控制
- 帶有自動啟用的css class的連結
- HTML5 歷史模式或hash模式, 在IE 9中自動降級
- 自定義的滾動行為
二、安裝
基於第一個vue-clhttp://www.cppcns.comi進行測試學習; 先檢視node modules中是否存在vue-router
vue-router是一個外掛包, 所以我們還是需要用npm/cnpm來進行安裝的。開啟命令列工具,進入你的專案目錄,輸入下面命令。
npm install vue-rouKLsyRter --save-dev
如果在一個模組化工程中使用它,必須要通過Vue.use()明確地安裝路由功能:
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter);
三、測試
1、先刪除沒有用的東西
2、componewww.cppcns.comnts 目錄下存放我們自己編寫的元件
3、定義一個Content.vue 的元件
<template> <div> <h1>內容頁</h1> </div> </template> <script> export default { name:"Content" } </script>
Main.vue元件
<template> <div> <h1>首頁</h1> </div> </template> <script> export default { name:"Main" } </script>
4、安裝路由,在src目錄下,新建一個資料夾:router,專門存放路由,配置路由index.js,如下
import Vue from'vue' //匯入路由外掛 import Router from 'vue-router' //匯入上面定義的元件 import Content from '../components/Content' import Main from '../components/Main' //安裝路由 Vue.use(Router) ; //配置路由 export default new Router({ routes:[ { //路由路徑 path:'/content',//路由名稱 name:'content',//跳轉到元件 component:Content },{ //路由路徑 path:'/main',//路由名稱 name:'main',//跳轉到元件 component:Main } ] });
5、在main.js中配置路由
import Vue from 'vue' import App from './App' //匯入上面建立的路由配置目錄 import router from './router'/程式設計客棧/自動掃描裡面的路由配置 //來關閉生產模式下給出的提示 Vue.config.productionTip = false; new Vue({ el:"#app",//配置路由 router,components:程式設計客棧{App},template:'<App/>' });
6、在App.vue中使用路由
<template> <div id="app"> <!-- router-link:預設會被渲染成一個<a>標籤,to屬性為指定連結 router-view:用於渲染路由匹配到的元件 --> <router-link to="/main">首頁</router-link> <router-link to="/content">內容</router-link> <router-view></router-view> </div> </template> <script> export default{ name:'App' } </script> <style></style>
以上就是Vue-router路由該如何使用的詳細內容,更多關於Vue-router路由使用的資料請關注我們其它相關文章!