国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > WEB開發 > 正文

vue-router: 嵌套路由

2024-04-27 15:04:21
字體:
來源:轉載
供稿:網友

模板抽離

我們已經學習過了Vue模板的另外定義形式,使用<template></template>。

<!-- 模板抽離出來 --> <template id="home"> <div>首頁</div> </template> <template id="news"> <div>新聞</div> </template>

然后js里定義路由組件的時候:

// 1. 定義(路由)組件。 const Home = { template: '#home' }; const News = { template: '#news' };

路由嵌套

實際應用界面,通常由多層嵌套的組件組合而成。 比如,我們 “首頁”組件中,還嵌套著 “登錄”和 “注冊”組件,那么URL對應就是/home/login/home/reg

<template id="home"> <!-- 注意:組件只能有一個根元素,所以我們包裝到這個div中 --> <div> <h2>首頁</h2> <router-link to="/home/login">登錄</router-link> <router-link to="/home/reg">注冊</router-link> <!-- 路由匹配到的組件將渲染在這里 --> <router-view></router-view> </div> </template>

這是訪問/home后的模板,其中我們需要把/home/login/home/reg渲染進來。 完成上面代碼后,HTML結構如下圖: 這里寫圖片描述

登錄和注冊2個組件 <template id="login"> <div>登錄界面</div> </template> <template id="reg"> <div>注冊界面</div> </template>//定義路由組件const Login = { template: '#login' }; const Reg = { template: '#reg' };

3.定義路由

// 2. 定義路由 const routes = [ { path: '/', redirect: '/home' }, { path: '/home', component: Home, children:[ { path: '/home/login', component: Login}, { path: '/home/reg', component: Reg} ] }, { path: '/news', component: News} ]

注意我們在home路由配置了它的children。這就是嵌套路由。

4.案例全部代碼如下:

<!DOCTYPE html><html><head> <title></title> <meta charset="utf-8"> <script src="http://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script></head><body> <div id="box"> <p> <router-link to="/home">home</router-link> <router-link to="/news">news</router-link> </p> <router-view></router-view> </div> <!-- 模板抽離出來 --> <template id="home"> <!-- 注意:組件只能有一個根元素,所以我們包裝到這個div中 --> <div> <h2>首頁</h2> <router-link to="/home/login">登錄</router-link> <router-link to="/home/reg">注冊</router-link> <!-- 路由匹配到的組件將渲染在這里 --> <router-view></router-view> </div> </template> <template id="news"> <div>新聞</div> </template> <template id="login"> <div>登錄界面</div> </template> <template id="reg"> <div>注冊界面</div> </template> <script type="text/javascript"> // 1. 定義(路由)組件。 const Home = { template: '#home' }; const News = { template: '#news' }; const Login = { template: '#login' }; const Reg = { template: '#reg' }; // 2. 定義路由 const routes = [ { path: '/', redirect: '/home' }, { path: '/home', component: Home, children:[ { path: '/home/login', component: Login}, { path: '/home/reg', component: Reg} ] }, { path: '/news', component: News} ] // 3. 創建 router 實例,然后傳 `routes` 配置 const router = new VueRouter({ routes // (縮寫)相當于 routes: routes }) // 4. 創建和掛載根實例。 // 記得要通過 router 配置參數注入路由, // 從而讓整個應用都有路由功能 const app = new Vue({ router }).$mount('#box') // 現在,應用已經啟動了! </script></body></html>

這里寫圖片描述


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 福贡县| 台东县| 兴安盟| 昌乐县| 屯留县| 临江市| 五原县| 福州市| 龙江县| 延寿县| 定襄县| 长寿区| 巴林左旗| 松滋市| 凌源市| 安陆市| 贺兰县| 思南县| 西吉县| 中西区| 蚌埠市| 天津市| 德化县| 五河县| 金平| 永宁县| 马尔康县| 桑日县| 富顺县| 桓台县| 洛阳市| 武清区| 赣榆县| 日喀则市| 长岛县| 许昌市| 清水县| 阳谷县| 新密市| 钟祥市| 五莲县|