【Vue】Vue Router 设定路由| 专案实作

为什麽要设定路由呢?

过去的网页大多是 Multi Page Application(多页式应用程序),一个网页画面对应到一个网址,当切换一个网址就换开启一份 HTML 文件。
相对的 SPA(Single Page Application 单页应用程序) 因为只有一个网页,所以我们需要告诉路由器什麽时候要将组件 (components) 反映到路由(routes),再渲染出网页画面。

可以从架构上看到 SPA 只会生成一支 index.html(APP.html),而网页的切换就是靠路由器来设定。
https://ithelp.ithome.com.tw/upload/images/20211227/20144231IQ0dMlRjQc.png

首先,引入 CDN

<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>

建立路由器实例

let router = new VueRouter({
})

绑定到根组件

new Vue ({
    el: '#app',
    router,
})

在路由器里定义路由的路线

  • path: 设定网址路径
  • name: 用来管理路由,因为有时候网址名称很长,乍看之下会不知道网页内容是什麽
  • compontent: 绑定每个路由要呈现的组件
// component 组件
let Home = {
    template: `<h1>主页</h1>`,
    data(){
        return{
        }
    }
}
let DetailPage = {
    template: `<h1>内页</h1>`,
    data(){
        return{
        }
    }
}

// 建立路由
let router = new VueRouter({
    routes:[
        {
            path: '/',
            name: 'index',
            component: Home
        },
        {   // 内页
            path: '/pdp/:id', 
            name: 'product-detail-page',
            component: DetailPage
        },
        {   
            path: '*',
            name: 'notFound',
            redirect: '/'  // 不符合以上路径,都会返回 index 页面
        }
    ]
})

// 绑定根组件
new Vue({
    el:'#app',
    router,
})

最後,将 router-view 对应到网页要呈现的位置,组件就会被渲染出来了

<div id='app'>
    <header></header>
    
    <router-view></router-view>
    
    <footer></footer>
</div>

参考来源:
https://next.router.vuejs.org/zh/guide/
https://www.youtube.com/watch?v=aYlihfn-Gmg


<<:  D15. 学习基础C、C++语言

>>:  30天程序语言研究

伸缩自如的Flask [day4] JWT

好的,你很辛苦的写了很多API function,但是你却不希望闲杂人等没事就call一下你的API...

LeetCode解题 Day18

282. Expression Add Operators https://leetcode.com...

[Day 27] 那些年欧洲退税的鸟事

去了 4 次,每次总是要买点东西才回家XDD 越买越大包,这就是另一件事情了... 有鉴於 4 次...

AWS Academy LMS 教材使用 - 教师

AWS Academy LMS 教材使用 - 教师 当开设一个 AWS Academ 课程并已经完成...

XML Parsers

在讲 annotation processor 的实作之前,我们要先了解一般的处理方式,通常是写 X...