Skip to content
On this page

Vue-Router

基本安裝

獨立安裝時:

cmd
npm install vue-router@4
or
yarn add vue-router@4

vite cli內安裝

cmd
npm add vue-router@next

基本配置

新增 router/index.js 檔案,這裡基本上要提醒 createWebHashHistorycreateWebHistory的差異,當瀏覽器所看到的路徑就可以分辨。 hashno_hash

js
// index.js
import { createRouter, createWebHashHistory } from 'vue-router';
// 2種引入router內的路由方式
import Home from '@/components/HelloWorld.vue';
import Other from '@/components/Other.vue';
import SomeLink from '@/components/somelink.vue'
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'frontDesk',
    component: () => import('@/components/About.vue'),
  },
   {
    path: '/othoer',
    name: 'Other',
    component: Other,
    children:[
      {path:'others',component: SomeLink}
    ]
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
export default router;

router 引入 src/main.js

js
...
import router from './router';
...
app.use(router)

接下來需要放進 App.vue 裡面,採用 <router-view> 這個標籤

html
<template>
...
<router-view></router-view>
...
</template>

TIP

建議 routes 路由設定可以分開來寫,這樣視覺上比較不會凌亂。分成 router/index.js 與router/routes.js。


參考