Vue 3 入门:从零搭建第一个组件

1. 环境准备

首先确保已安装 Node.js(建议 v16+):

node -v  # 验证版本
npm -v   # 验证包管理器

2. 创建 Vue 3 项目

使用 Vite 快速搭建:

npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
npm install
npm run dev

3. 创建第一个组件

src/components 目录新建 MyFirstComponent.vue

<template>
  <div class="greeting-box">
    <h1>{{ title }}</h1>
    <p>计数器: {{ count }}</p>
    <button @click="increment">点击+1</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

// 响应式数据
const count = ref(0)
const title = ref('我的第一个Vue 3组件')

// 方法
const increment = () => {
  count.value++
}
</script>

<style scoped>
.greeting-box {
  border: 2px solid #42b983;
  padding: 20px;
  border-radius: 8px;
  max-width: 400px;
  margin: 0 auto;
}
button {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
</style>

4. 在 App.vue 中使用组件

修改 src/App.vue

<template>
  <div id="app">
    <MyFirstComponent />
  </div>
</template>

<script setup>
import MyFirstComponent from './components/MyFirstComponent.vue'
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5. 运行项目
npm run dev

访问 http://localhost:5173 即可看到组件效果:

  1. 显示标题 "我的第一个Vue 3组件"
  2. 初始计数器为 0
  3. 点击按钮时计数器增加
核心概念解析
  1. <script setup>
    Vue 3 的组合式 API 语法糖,无需显式暴露变量和方法

  2. ref()
    创建响应式数据引用,修改时自动更新视图

  3. 模板语法
    {{ }} 插值表达式绑定数据

  4. @click
    事件绑定指令,等价于 v-on:click

  5. scoped 样式
    CSS 作用域限制,避免样式污染

进阶建议
  1. 尝试添加计算属性:
<script setup>
import { computed } from 'vue'
const doubleCount = computed(() => count.value * 2)
</script>

  1. 添加 props 实现组件复用:
<script setup>
defineProps({
  initialCount: {
    type: Number,
    default: 0
  }
})
</script>

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐