Vue vue-router 路由創建並使用


vue-router說明

Vue Router 是Vue.js官方的路由管理器。它和Vue.js的核心深度集成,讓構建單頁面應用變得易如反掌。包含功能有:

  • 嵌套的路由/視圖表
  • 模塊化的、基於組件的路由配置
  • 路由參數、查詢、通配符
  • 基於Vue.js過度系統的視圖過度效果
  • 細粒度的導航控制
  • 帶有自動激活的CSS class 的鏈接
  • HTML5 歷史模式或hash模式,在IE6中自動降級
  • 自定義的滾動條行為

安裝

vue-router是一個插件包,所以我們還是需要用 npm/cnpm進行安裝。

npm install vue-router --save-dev

在一個模塊化工程中使用它,必須通過 Vue.use(“路由名稱”) 明確地安裝路由功能

vue-router使用

1.在src文件夾下建立components組件文件夾,分別建立Comtent.vue和Main.vue兩個組件

<template>
  <h1>內容頁</h1>
</template>

<script>
    export default {
        name: "Content"
    }
</script>

<style scoped>

</style>
<template>
    <h1>首頁</h1>
</template>

<script>
    export default {
        name: "Main"
    }
</script>

<style scoped>

</style>

2.在src文件夾下建立router文件夾,在文件夾下建立 index.js用於路由頁面的跳轉配置

import Vue from 'vue'
import VueRouter from 'vue-router'

//導入自定義組件
import Content from '../components/Content'
import Main from '../components/Main'

//安裝路由,顯示引用
Vue.use(VueRouter);


//配置導出路由
export default new VueRouter({
  routes:[
    {
      //路由路徑
      path:'/content',
      //自定義路由名稱
      name:'content',
      //路由跳轉的組件
      component:Content
    },
    {
      //路由路徑
      path:'/main',
      //自定義路由名稱
      name:'main',
      //路由跳轉的組件
      component:Main
    }
  ]
});

3.在main.js中引用自定義路由配置並開啟

import Vue from 'vue'
import App from './App'
import router from './router'//導入自定義路由配置

new Vue({
  el: '#app',
  //配置路由
  router,
  components: { App },
  template: '<App/>'
})

4.在App.vue中配置並測試路由,主要利用<router-link to="/路由配置中的path">XX</router-link>

<template>
  <div id="app">
    <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>
#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>

注意:<router-link> 和<router-view>兩個標簽缺一不可

目錄結構如圖:

 

 測試結果如圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM