1. 导入组件#

在 Vue 3 中,使用单文件组件(SFC,.vue 文件)时,导入并直接使用其他组件的方式非常简单:

创建组件(如 MyButton.vue

<!-- src/components/MyButton.vue -->
<template>
  <button @click="handleClick" class="my-button">
    <slot>默认按钮</slot>
  </button>
</template>

<script setup>
const handleClick = () => {
  console.log('按钮被点击了')
}
</script>

<style scoped>
.my-button {
  border-radius: 4px;
}
</style>

在父组件中导入并注册使用

<!-- src/App.vue -->
<template>
  <div>
    <h1>欢迎来到 Vue 3</h1>
    <MyButton>点击我</MyButton>
  </div>
</template>

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

script setup 语法糖会自动注册引入的组件,无需再手动写 components: {}

2. 传递 props#

子组件:ConfirmDialog.vue

<template>
  <div v-if="visible" class="dialog-backdrop">
    <div class="dialog">
      <p>{{ message }}</p>
      <button @click="onConfirm">确认</button>
      <button @click="onCancel">取消</button>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  visible: Boolean, // 控制是否显示
  message: {
    type: String,
    default: '你确定要执行这个操作吗?'
  },
  onConfirm: Function, // 点击确认的回调
  onCancel: Function   // 点击取消的回调
})
</script>

<style scoped>
.dialog-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
}
.dialog {
  background: white;
  padding: 20px;
  margin: 200px auto;
  width: 300px;
  border-radius: 8px;
  text-align: center;
}
</style>

父组件:使用并传入各种 props

<template>
  <div>
    <button @click="showDialog = true">删除文件</button>

    <ConfirmDialog
      :visible="showDialog"
      message="你确定要删除这个文件吗?"
      :onConfirm="handleConfirm"
      :onCancel="() => showDialog = false"
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import ConfirmDialog from './components/ConfirmDialog.vue'

const showDialog = ref(false)

const handleConfirm = () => {
  alert('已删除!')
  showDialog.value = false
}
</script>
类型 示例
字符串 message="确定删除?"
布尔值 :visible="true"
函数 :onConfirm="handleFn"
箭头函数 :onCancel="() => {}"
对象/数组 :data="{ id: 1 }"