vue之簡易的前端路由
阿新 • • 發佈:2022-06-06
app.vue
<template> <div> <h1>App 根元件</h1> <a href="#/home">Home</a> <a href="#/movie">Movie</a> <a href="#/about">About</a> <hr /> <component :is="comName"></component> </div></template> <script> import MyHome from './MyHome.vue' import MyMovie from './MyMovie.vue' import MyAbout from './MyAbout.vue' export default { name: 'MyApp', data() { return { comName: 'MyHome', } }, created() { // 監聽 hash 值變化的事件 window.onhashchange = () =>{ // 通過 location.hash 獲取到最新的 hash 值,並進行匹配 switch (location.hash) { case '#/home': this.comName = 'MyHome' break case '#/movie': this.comName = 'MyMovie' break case '#/about': this.comName = 'MyAbout' break } } }, components: { MyHome, MyMovie, MyAbout, }, }</script> <style></style>