这里是完整的目录图片,由于整篇文章篇幅太长,拆分成了几篇来展示
2. 自动注册子组件
子组件代码
<!-- 子组件 -->
<template>
<div> this is child component </div>
</template>
<script>
</script>
<style>
</style>
父组件
<template>
<div>
<h2>i am father component</h2>
<!-- 使用子组件 -->
<Child></Child>
</div>
</template>
Vue 3 setup() 语法
Vue3 语法要求在引入子组件的时候需要先在 script 当中 import 导入,并在 components 对象当中绑定注册对应的组件,才能在模板当中使用,
<script>
import {
defineComponent, ref } from 'vue';
import Child from './child.vue'
export default defineComponent({
components: {
Child
},
setup() {
return {
}
}
});
<script setup>
语法糖的写法
直接省略了子组件注册的过程,直接导入就可以了
<script setup>
import Child from './child.vue'
</script>
小结
在 script setup 当中,引入的组件可以直接使用,无需通过 components 进行注册,而且在 script setup 范围内的值也能直接作为自定义组件的标签名使用,不需要卸载 component 对象当中
命名空间组件
3. defineProps , defienEmits()
script setup 分别提供了 defineProps 以及 defineEmits 来代替 props 接收父组件传递的数据 (父组件 ⇒ 子组件 传参)
- defineProps 来代替 props 接收父组件传递的数据 (父组件 ⇒ 子组件 传参)
- defineEmits 来代替 emit 完成子组件向父组件传递数据 (子组件向外暴露数据)
defineProps 父子传值
Vue 3 setup() 语法
父组件
<!-- 父组件 -->
<template>
<div>