VueRouter 命名視圖
1. 前言
本小節我們介紹如何使用 VueRouter 命名視圖。包括如何定義命名視圖、如何使用命名視圖。本節的學習內容相對簡單,相信同學們看完本小節,并對小節中的案例自己實現一遍就可以熟練掌握了。
2. 定義視圖名
2.1 默認視圖
在之前的小節中,我們學習了如何使用 <router-view/>
來承載路由分發的內容。我們并沒有給 <router-view/>
指定一個 name 屬性,實際上他有一個默認的屬性 default,我們以一個簡單的實例來驗證這一點:
<!DOCTYPE html>
<html lang>
<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>Document</title>
</head>
<body>
<div id="app">
<div>
<router-link to="/index">首頁</router-link>
<router-link to="/article">文章</router-link>
</div>
<router-view></router-view>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script type="text/javascript">
const Index = Vue.component('index', {
template: '<div>Hello,歡迎使用慕課網學習 Vue 教程!</div>',
})
const Article = Vue.component('myArticle', {
template: `<ul><li>1. Vue 計算屬性的學習</li><li>2. React 基礎學習</li></ul>`,
})
const routes = [
{ path: '/index', components: {default: Index} },
{ path: '/article', components: {default: Article} }
]
const router = new VueRouter({
routes: routes
})
var vm = new Vue({
el: '#app',
router: router,
data() {
return {}
}
})
</script>
</html>
代碼解釋:
HTML 代碼第 12-13 行,我們定義了兩個跳轉鏈接。
HTML 代碼第 15 行,我們使用 <router-view></router-view>
組件來渲染匹配組件。
JS 代碼第 5-7 行,我們定義了組件 Index。
JS 代碼第 9-11 行,我們定義了組件 Article。
JS 代碼第 13-16 行,我們定義了路由數組:
- 1. 首頁路由,地址為 ‘/index’,默認視圖匹配組件 Index。
- 2. 文章路由,地址為 ‘/article’,默認視圖匹配組件 Article。
JS 代碼第 18-20 行,創建 router 實例,然后傳 routes
配置。
JS 代碼第 24 行,通過 router 配置參數注入路由。
2.2 具名視圖
除了使用默認視圖名外,我們還可以給視圖指定一個名字:
<router-view name="name"/>
<!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>Document</title>
</head>
<body>
<div id="app">
<div>
<router-link to="/index">首頁</router-link>
<router-link to="/article">文章</router-link>
</div>
<router-view name="view"></router-view>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script type="text/javascript">
const Index = Vue.component('index', {
template: '<div>Hello,歡迎使用慕課網學習 Vue 教程!</div>',
})
const Article = Vue.component('myArticle', {
template: `<ul><li>1. Vue 計算屬性的學習</li><li>2. React 基礎學習</li></ul>`,
})
const routes = [
{ path: '/index', components: {view: Index} },
{ path: '/article', components: {view: Article} }
]
const router = new VueRouter({
routes: routes
})
var vm = new Vue({
el: '#app',
router: router,
data() {
return {}
}
})
</script>
</html>
代碼解釋
我們對上述案例做一個簡單的修改:
- 指定
<router-view />
的視圖名為 view。 - 定義路由信息的時候,指定視圖 view 匹配對應組件。
3. 小結
本節,我們帶大家學習了 VueRouter 命名視圖的使用方法。主要知識點有以下幾點:
- 通過 name 屬性指定視圖名稱。
- 通過路由
components
指定各具名視圖對應匹配的組件。