Vue.js路由組件vue-router使用方法詳解
使用Vue.js + vue-router 創(chuàng)建單頁應用是非常簡單的。只需要配置組件和路由映射,然后告訴 vue-router 在哪里渲染即可。
一、普通方式基本例子:
<!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() 創(chuàng)建的組件構造器,
// 或者,只是一個組件配置對象。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 創(chuàng)建 router 實例,然后傳 `routes` 配置
const router = new VueRouter({
routes // (縮寫)相當于 routes: routes
})
// 4. 創(chuàng)建和掛載根實例。
// 記得要通過 router 配置參數(shù)注入路由,
// 從而讓整個應用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 現(xiàn)在,應用已經(jīng)啟動了!
</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 },
]
//使用路由規(guī)則
const router = new VueRouter({
routes
})
//加載路由規(guī)則
new Vue({
router,
el: '#app',
render:h => h(App)
})
然后運行npm run dev查看效果吧。
本文已被整理到了《Vue.js前端組件學習教程》,歡迎大家學習閱讀。
關于vue.js組件的教程,請大家點擊專題vue.js組件學習教程進行學習。
更多vue學習教程請閱讀專題《vue實戰(zhàn)教程》
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

