1. 程式人生 > >三十二、Vue-router入門

三十二、Vue-router入門

                                    Vue-router入門


      由於Vue在開發時對路由支援的不足,後來官方補充了vue-router外掛,它在Vue的生態環境中非常重要,在實際開發中只要編寫一個頁面就會操作vue-router。要學習vue-router就要先知道這裡的路由是什麼?這裡的路由並不是指我們平時所說的硬體路由器,這裡的路由就是SPA(單頁應用)的路徑管理器。再通俗的說,vue-router就是我們WebApp的連結路徑管理系統

      有的小夥伴會有疑慮,為什麼我們不能像原來一樣直接用<a></a>標籤編寫連結哪?因為我們用Vue作的都是單頁應用,就相當於只有一個主的index.html頁面,所以你寫的<a></a>標籤是不起作用的,你必須使用vue-router來進行管理。

1、安裝vue-router

      vue-router是一個外掛包,所以我們還是需要用npm來進行安裝的。開啟命令列工具,進入你的專案目錄,輸入下面命令

    npm install vue-router --save-dev

2、router/index.js檔案

      我們用vue-cli生產了我們的專案結構,你可以在src/router/index.js檔案,這個檔案就是路由的核心檔案,我們先解讀一下它。
      這個檔案定義了我們的所有路由。

import Vue from 'vue'   //引入Vue
import Router from 'vue-router'  //引入vue-router
import Hello from '@/components/Hello'  //引入根目錄下的Hello.vue元件
import Hi from '@/components/Hi'

Vue.use(Router)  //Vue全域性使用Router

export default new Router({
  routes: [              //配置路由,這裡是個數組
    {                    //每一個連結都是一個物件
      path: '/',         //連結路徑:使用這個連結可以跳轉到component宣告的頁面
      name: 'Hello',     //路由名稱
      component: Hello   //對應的元件模板:跳轉的頁面
    },{
      path:'/hi',
      name:'Hi',
      component:Hi
    }
  ]
})

3、路由跳轉的頁面

Hi.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>
<script>
  export default {
    name: 'hi',
    data () {
      return {
        msg: 'Hi, I am 楊胖子'
      }
    }
  }
</script>
<style scoped>
</style>

4、App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">

    <p>導航 :
      <router-link to="/">首頁</router-link>     
      <!--宣告跳轉的連結(在router/index.js檔案定義)-->
      <router-link to="/Hi">Hi頁面</router-link>
    </p>
    <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>