1. 程式人生 > 其它 >vue之簡易的前端路由

vue之簡易的前端路由

app.vue

<template>
  <div>
    <h1>App 根元件</h1>

    <a href="#/home">Home</a>&nbsp; <a href="#/movie">Movie</a>&nbsp; <a href="#/about">About</a>&nbsp;
    <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>