vue3專案中配置路由的步驟
阿新 • • 發佈:2022-05-08
1.先建立專案a資料夾:
(1)我在這裡使用的是vite方法配置的vue:
npm init vite-app a
cd a
npm i
npm run dev
(2)在新建的資料夾a裡安裝:
npm i vue-router
刪減清理檔案
(3)在components中新建3個vue元件並新增內容:
Bar.vue,Foo.vue,User.vue
(4)在src中新建router資料夾並在資料夾中新建index.js
import {createRouter,createWebHashHistory} from "vue-router" //1.引入配置路由的兩個方法-------------------------------------------------------------------------------------- //2.引入單元件 import Bar from "../components/Bar.vue"; import Foo from "../components/Foo.vue"; import User from "../components/User.vue"; --------------------------------------------------------------------------------------//3.兩種寫法: 1.合寫 const router=createRouter({ history:createWebHashHistory(), linkActiveClass:"router-active", routes:[ //{path:'/',redirect:'/home'}, {path:'/bar',component:Bar}, {path:'/foo',component:Foo}, {path:'/user',component:User} //觸發bar時出現Bar元件 ] }) ----------------------------------------------------------------------2.分寫 //建立路由資訊物件陣列routes const routes = [ {path: '/bar', component: Bar}, {path: '/foo', component: Foo}, {path: '/user', component: User} //觸發bar時出現Bar元件 ] //建立路由管理器物件 const router=createRouter({ history: createWebHashHistory(), routes }) --------------------------------------------------------------------------- //4.最後將路由管理器物件對外輸出 export default router
注意 / 後連線名要相對應
(6)在main.js中引入router來關聯起index.js和vue:
import router from "./router"
將配置好的路由器管理物件與當前vue專案相關聯:
createApp(App).use(router).mount('#app')
(7)在app.vue的<template>中引入
<router-link to="/bar">首頁</router-link> <router-link to="/foo">電影</router-link> <router-link to="/user">關於</router-link> <router-view/>