路由router
一、說明
學習的時候,盡量的打開官方的文檔
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,讓構建單頁面應用變得易如反掌。包含的功能有:
- 嵌套的路由/視圖表
- 模塊化的、基於組件的路由配置
- 路由參數、查詢、通配符
- 基於 Vue.js 過渡系統的視圖過渡效果
- 細粒度的導航控制
- 帶有自動激活的 CSS class 的鏈接
- HTML5 歷史模式或 hash 模式,在 IE9 中自動降級
- 自定義的滾動條行為
二、router的安裝
vue-router 是一個插件包,所以我們還是需要用 npm/cnpm 來進行安裝的。打開命令行工具,進入你的項目目錄,輸入下面命令:
# 這里我是使用idea控制台使用命令行進行安裝的 # cnpm install vue-router --save-dev
驗證:查看node_modules中是否存在 vue-router
三、router的跳轉
1、在component目錄下編寫vue組件
刪除我們不需要的組件
創建Some.vue跟Main.vue兩個組件
Main.vue:
<template> <div> <h1>首頁</h1> </div> </template> <script> // 路由的導出 export default { name: "Main" } </script> <style scoped> </style>
Some.vue:
<template> <div> <h1>內容頁</h1> </div> </template> <script> // 路由的導出 export default { name: "Some" } </script> <style scoped> </style>
2、管理路由,在src目錄下,新建一個文件夾 : router,專門存放路由
index.js:路由的主配置文件
/*配置路由*/ import Vue from 'vue' // 導入路由插件 import Router from 'vue-router' // 導入上面定義的組件 import vueSome from '../components/Some' import vueMain from '../components/Main' // 安裝路由 Vue.use(Router); // 配置路由 export default new Router({ routes: [ { // 路由請求路徑 path: '/some', // 路由名稱,可以省略不寫 name: 'some', // 跳轉到組件 component: vueSome }, { // 路由請求路徑 path: '/main', // 路由名稱,可以省略不寫 name: 'main', // 跳轉到組件 component: vueMain } ] });
3、在main.js中配置路由
import Vue from 'vue' import App from './App' // 導入上面創建的路由配置目錄 import router from './router/index' //來關閉生產模式下給出的提示 Vue.config.productionTip = false; new Vue({ el: '#app', // 配置路由 router, components: { App }, template: '<App/>' });
4、在app.vue中使用路由
<template> <div id="app"> <!-- router-link: 默認會被渲染成一個 <a> 標簽,to 屬性為指定鏈接 router-view: 用於渲染路由匹配到的組件 --> <h1>WelCome!</h1> <router-link to="/main">首頁</router-link> <router-link to="/some">內容</router-link> <router-view></router-view> </div> </template> <script> export default { name: 'App' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
5、啟動程序
npm run dev