Vue.js路由群組件vue-router如何使用?

來源:互聯網
上載者:User

標籤:

使用 Vue.js + vue-router 建立單頁應用是非常簡單的,只需要配置組件和路由映射,然後告訴 vue-router 在哪裡渲染即可。本文和大家分享的就是vue-router的相關使用方法,希望對大家學習Vue.js有所協助。

一 普通方式基本例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue-router使用方法</title>
</head>
<body>
  <div id="app">
    <h1>Hello App!</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>
    </p>
    <!-- 路由出口 -->
    <!-- 路由匹配到的組件將渲染在這裡 -->
<router-view></router-view>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue-router"></script>
  <script>

    // 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
})

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

    // 現在,應用已經啟動了!
</script>
</body>
</html>
二 塊化機制編程基本例子,以在vue-cli中的使用方法為例

安裝 vue-router 外掛程式
# npm install vue-router --save-dev
在src檔案夾下面的components檔案夾下建立Foo.vue、Bar.vue兩個組件,在Foo組件寫入以下內容
<template>
    <div>foo</div>
</template>
在Bar.vue組件中寫入以下內容

<template>
    <div>bar</div>
</template>
開啟src檔案夾下面的app.vue檔案,修改代碼為

<template>
  <div id="app">
    <router-view
      class="view"
      keep-alive
      transition
      transition-mode="out-in">
    </router-view>
  </div>
</template>
這裡用 router-view 來把剛才建立的兩個頁面載入到這裡來,修改src檔案夾下面的main.js檔案
import Vue from ’vue’
import App from ’./App’
//引用路由外掛程式
import VueRouter from ’vue-router’

//使用路由外掛程式
Vue.use(VueRouter)

//引入組件  
import Foo from ’./components/Foo’
import Bar from ’./components/Bar’

const routes = [
  { path: ’/foo/’ , component: Foo },
  { path: ’/bar/’ , component: Bar },
]

//使用路由規則
const router = new VueRouter({
  routes
})
//載入路由規則
new Vue({
    router,
    el: ’#app’,
    render:h => h(App)
})
然後運行 npm run dev 查看效果吧

來源:劉寧個人部落格

Vue.js路由群組件vue-router如何使用?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.