Vue基础(前端教程①-路由)

项目结构

复制代码
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 应用的 "全局配置中心",负责告诉应用:"哪些资源是全局可用的,如何启动整个应用"。但它本身不是全局变量的容器,而是控制全局行为的入口。

相关推荐
EndingCoder几秒前
泛型类和高级用法
linux·运维·前端·ubuntu·typescript
ℋᙚᵐⁱᒻᵉ鲸落6 分钟前
【Vue3】Element Plus 表单显示自定义校验错误
前端·javascript·vue.js
程序员小寒7 分钟前
聊一聊 CommonJS 和 ES6 Module
前端·ecmascript·es6
Java后端的Ai之路8 分钟前
【AI应用开发工程师】-Gemini写前端的一个坑
前端·人工智能·gemini·ai应用开发工程师
亿元程序员8 分钟前
最近很火的一个拼图游戏,老板让我用Cocos3.8做一个...
前端
m0_748250039 分钟前
C++ Web 编程
开发语言·前端·c++
切糕师学AI9 分钟前
Vue 中的响应式布局
前端·javascript·vue.js
行者9612 分钟前
Flutter适配OpenHarmony:跨平台开发热门标签组件,从数据到交互的完整实现
前端·flutter·harmonyos·鸿蒙
晷龙烬13 分钟前
Vue组件使用三步走:创建、注册、使用(Vue2/Vue3双版本详解)
前端·javascript·vue.js
前端 贾公子15 分钟前
微信小程序webview访问的url从https变成http原因排查
前端