Vue-Router路由學習
目錄檔案:
main.js檔案
// 從vue中匯入建立app方法
import { createApp } from 'vue'
import App from './App.vue'
// vue-router匯入建立路由方法
import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
import HomePage from './pages/HomePage.vue'
import ArticleListPage from './pages/ArticleListPage.vue'
import SearchPage from './pages/SearchPage.vue'
//建立路由集,路由配置
// path路由跳轉位置,conponent對應元件
const routes =[
{
path:"/",
component:HomePage,
},
{
path:"/article-list",
component: ArticleListPage,
},
{
path:"/search",
component: SearchPage,
}
]
//使用匯入的createRouter方法,建立一個router,router負責管理路由
const router = createRouter({
//history物件,就是瀏覽器訪問的URL,
// createWebHashHistory路由模式路徑帶#號,而createWebHistory不帶#號
history:createWebHistory(),
//前面的routes是路由集鎖定位置,後面的routes是路由陣列
routes:routes,
})
//createApp(App).mount('#app')
//建立app,使用路由
createApp(App).use(router).mount("#app")
app.vue
<script setup>
//匯入
import HelloWorld from './components/HelloWorld.vue'
import HomePage from './pages/HomePage.vue'
</script>
<template>
<div id="div1">
<h1>News Demo</h1>
<div id="nav">
<!-- 路由到當前頁面 -->
<router-link to="/">Home</router-link>
<!-- 路由到某個頁面 -->
<router-link to="/article-list">Article List</router-link>
<router-link to="/search">Search</router-link>
</div>
<div id="container">
<!-- routrt-view替代a標籤,但又有不同,router-view在當前頁面跳轉,a標籤在其他頁面跳轉 -->
<!-- 切換不同的元件顯示不同的內容,地址同樣會改變 -->
<!-- 路由元件渲染部分,就是點選那部分路由就在這顯示 -->
<router-view></router-view>
</div>
<div id="footer">
<hr />
<p>Copyright © Justin 2022-2023</p>
</div>
</div>
</template>
<style>
#div1 {
width: 600px;
margin: 0 auto;
}
/* CSS */
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
#container {
text-align: left;
}
#container h2 {
text-align: center;
}
#nav a {
display: inline-block;
border: 1px solid #ccc;
width: 120px;
height: 30px;
line-height: 30px;
margin: 0 20px;
text-decoration: none;
color: #337ab7;
}
#nav a:hover {
color: white;
}
</style>