1. 导入
要使用一个子组件,需要在父组件中进行导入
<script setup>
import MyComponent from './MyComponent.vue'
</script><template><MyComponent />
</template>
2. 传递 props
在使用 <script setup> 的单文件组件中,props 可以使用 defineProps() 宏来声明,可以传入对象对 props 进行校验。
- 父组件
<MyComponent :title="..." :comments="..." :handleClick="...", :handle-cancel="..."
/>
- 子组件 MyComponent
<script setup>
const props = defineProps({title: {type: String,required: true,},comments: [Array, null],handleClick: Function, // String、Number、Boolean、Array、Object、Date、FunctionhandleCancel: Function,
})
</script><template><button @click="props.handleClick">{{ props.title }}</button>
</template>
向子组件传递 props 时可以使用 camelCase 形式 (handleClick),但实际上为了和 HTML attribute 对齐,我们通常会将其写为 kebab-case 形式(handle-cancel)。props的名字提供了自动的格式转换。
3. 传递事件
除了通过 props 的方法传递事件函数之外,还可以通过 defineEmits() 宏来声明要触发的事件。
- 父组件
<MyComponent @handle-cancel="..." />
- 子组件 MyComponent
<script setup>
const emit = defineEmit(['handleCancel'])
</script><template>
<button @click="emit('handleCancel')">取消</button>
</template>
事件的名字提供了自动的格式转换。注意子组件触发了一个以 camelCase 形式命名的事件,但在父组件中可以使用 kebab-case 形式来监听。
4. 插槽
- 父组件
<MyButton>查询</MyButton>
- 子组件 MyButton
<button><slot/> <!-- 查询 -->
</button>
使用 <slot> 作为一个占位符,父组件传递进来的内容就会渲染在这里。
5. props 透传
父组件使用 provide() 函数为子组件提供数据,子组件使用 inject() 函数注入上层组件提供的数据,从而实现 props 逐级透传
- 父组件
<script setup>
import { provide } from 'vue'provide('message', 'Hello World') // 注入名,值
</script>
- 子组件
<script setup>
import { inject } from 'vue'const message = inject('message')
</script>
在实际开发过程中,建议使用 Symbol 作为注入名来避免潜在的冲突。