Vue 路由(router)

Vue.js 路由容許咱們經過不一樣的 URL 訪問不一樣的內容。css

經過 Vue.js 能夠實現多視圖的單頁Web應用(single page web application,SPA)。html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 路由(router)</title>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.min.js"></script>
</head>
<body>
<div id="app">
  <h1>Vue 路由實例</h1>
  <p>
    <!-- 使用 router-link 組件來導航. -->
    <!-- 經過傳入 `to` 屬性指定連接. -->
    <!-- <router-link> 默認會被渲染成一個 `<a>` 標籤 -->
    <router-link to="/name">姓名</router-link>
    <router-link to="/job">工做</router-link>
  </p>
  <!-- 路由出口 -->
  <!-- 路由匹配到的組件將渲染在這裏 -->
  <router-view></router-view>
</div>

<script>
// 0. 若是使用模塊化機制編程,導入Vue和VueRouter,要調用 Vue.use(VueRouter)

// 1. 定義(路由)組件。
// 能夠從其餘文件 import 進來
const Name = { template: '<div>徐同保</div>' }
const Job = { template: '<div>Web前端</div>' }

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

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

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

// 如今,應用已經啓動了!
</script>
</body>
</html>



相關文章
相關標籤/搜索