項目結構
src/├── router/│ └── index.js # 路由配置├── components/│ ├── Home.vue # 首頁組件│ ├── About.vue # 關于頁組件│ └── Contact.vue # 聯系頁組件├── App.vue # 根組件(含導航欄)└── main.js # 入口文件
1. 路由配置文件?router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../components/Home.vue'
import About from '../components/About.vue'
import Contact from '../components/Contact.vue'const routes = [{ path: '/', name: 'Home', component: Home },{ path: '/about', name: 'About', component: About },{ path: '/contact', name: 'Contact', component: Contact }
]const router = createRouter({history: createWebHistory(),routes
})export default router
2. 組件文件?components/
Home.vue
<template><div class="page-container"><h1>首頁</h1><p>歡迎訪問我們的網站!</p><button @click="greet">點擊打招呼</button></div>
</template><script>
export default {name: 'Home',methods: {greet() {alert('Hello!')}}
}
</script><style scoped>
.page-container {padding: 20px;
}
</style>
3. 根組件?App.vue
<template><div id="app"><!-- 導航欄 --><nav class="navbar"><router-link to="/" class="nav-link">首頁</router-link><router-link to="/about" class="nav-link">關于</router-link><router-link to="/contact" class="nav-link">聯系</router-link></nav><!-- 路由出口:顯示當前頁面 --><router-view /></div>
</template><script>
export default {name: 'App'
}
</script><style>
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;margin-top: 50px;
}.navbar {background-color: #f8f9fa;padding: 10px 0;margin-bottom: 20px;
}.nav-link {margin: 0 15px;text-decoration: none;color: #333;font-weight: 500;
}.nav-link.router-link-exact-active {color: #42b983;border-bottom: 2px solid #42b983;padding-bottom: 2px;
}
</style>
4. 入口文件?main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'// 創建應用并使用路由
createApp(App).use(router).mount('#app')
所有需要在整個應用中生效的功能(如路由、全局樣式、插件),都需要在?main.js
?中通過?app.use()
?或?app.component()
?等方法 “啟用”,否則無法在應用中全局使用。
main.js
?是 Vue 應用的 “全局配置中心”,負責告訴應用:“哪些資源是全局可用的,如何啟動整個應用”。但它本身不是全局變量的容器,而是控制全局行為的入口。