在現在常用的框架中,其實都是單頁應用,也就是入口都是index.html, 僅此一個html文件而已。可是實際在使用過程中,又是存在不同的頁面,那麼這是如何實現的呢?這就是router的功勞了,React裏面有react-router,vue有vue-router。
Vue Router 是 Vue.js 的官方路由。它與 Vue.js 核心深度集成,讓用 Vue.js 構建單頁應用變得輕而易舉。功能包括:
- 嵌套路由映射
- 動態路由選擇
- 模塊化、基於組件的路由配置
- 路由參數、查詢、通配符
- 展示由 Vue.js 的過渡系統提供的過渡效果
- 細緻的導航控制
- 自動激活 CSS 類的鏈接
- HTML5 history 模式或 hash 模式
- 可定製的滾動行爲
- URL 的正確編碼
安裝
npm install vue-router@4
文件目錄
router/index.js
import { createRouter,createWebHashHistory} from "vue-router";
const routes = [
{
path: "/page1",
name: "page1",
component: import("../components/page1")
},
{
path: "/page2",
name: "page2",
component: import("../components/page2")
}
]
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
import router from './router/index.js'
const app = createApp(App);
app.use(store);
app.use(router);
app.mount('#app');
App.vue
<template>
<div>
<button @click="btn1">按鈕1</button>
<button @click="btn2">按鈕2</button>
<router-view></router-view>
</div>
</template>
<script>
import { useRouter } from "vue-router";
export default {
setup() {
const router = useRouter();
return {
router,
};
},
methods: {
btn1() {
this.router.push({
name: "page1",
});
},
btn2() {
this.router.push({
name: "page2",
});
},
},
};
</script>
page1.vue
<template>
<div>page1</div>
</template>
結果: