Vue Router 簡單例子

一、起步

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

包含的功能有:
(比較晦澀難懂,隨着慢慢熟悉vue,再回來細細品讀)html

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

二、實例

如下代碼直接新建一個html,複製黏貼便可
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue router</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
  <h1>Hello sz!</h1>
  <p>
    <!-- 使用 router-link 組件來導航. -->
    <!-- 經過傳入 `to` 屬性指定連接. -->
    <!-- <router-link> 默認會被渲染成一個 `<a>` 標籤 -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
    <br/><br/>路由匹配到的組件將渲染在這裏下面
  </p>
  <!-- 路由出口 -->
  <!-- 路由匹配到的組件將渲染在這裏 -->
  <router-view></router-view>
</div>
</body>
<script>
  // 0. 若是使用模塊化機制編程,導入Vue和VueRouter,要調用 Vue.use(VueRouter)

  // 1. 定義 (路由) 組件。
  // 能夠從其餘文件 import 進來
  const Foo = { template: '<div>foo</div>' }
  const Bar = { template: '<div>bar</div>' }

  // 2. 定義路由
  // 每一個路由應該映射一個組件。 其中"component" 能夠是
  // 經過 Vue.extend() 建立的組件構造器,
  // 或者,只是一個組件配置對象。
  // 咱們晚點再討論嵌套路由。
  const routes = [
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar }
  ]

  // 3. 建立 router 實例,而後傳 `routes` 配置
  // 你還能夠傳別的配置參數, 不過先這麼簡單着吧。
  const router = new VueRouter({
    //routes // (縮寫) 至關於 routes: routes
    routes: routes
  })

  // 4. 建立和掛載根實例。
  // 記得要經過 router 配置參數注入路由,
  // 從而讓整個應用都有路由功能
  const app = new Vue({
    router
  }).$mount('#app')

  // 如今,應用已經啓動了!

// 擴展
// 經過 this.$router 訪問路由器   this.$route.params.username
// 也能夠經過 this.$route 訪問當前路由  this.$router.push('/')

</script> 
</html>
相關文章
相關標籤/搜索