这里是完整的目录图片,由于整篇文章篇幅太长,拆分成了几篇来展示
子组件代码
this is child component
父组件
i am father component
Vue 3 setup() 语法
Vue3 语法要求在引入子组件的时候需要先在 script 当中 import 导入,并在 components 对象当中绑定注册对应的组件,才能在模板当中使用,
在 script setup 当中,引入的组件可以直接使用,无需通过 components 进行注册,而且在 script setup 范围内的值也能直接作为自定义组件的标签名使用,不需要卸载 component 对象当中
script setup 分别提供了 defineProps 以及 defineEmits 来代替 props 接收父组件传递的数据 (父组件 ⇒ 子组件 传参)
Vue 3 setup() 语法
父组件
i am father component
子组件
this is child component {{ message }}
可以看到我们在子组件当中对于父组件传过来的数据是从 setup() 方法的 props 参数中获取的,那么在 setup script 语法当中没有 setup() 方法,自然也就无法像之前一样通过 props 参数
来获取到 父 ==> 子的数据
子组件 Vue 3 setup() 语法 父组件 子组件 子组件 注意 : defineProps defineEmits 只在 他们不需要 ! 不需要 ! 不需要 ! 手动导入, 自动在 defineProps 和 defineEmits 在选项传入后,会提供恰当的类型推导。 传入到 defineProps 和 defineEmits 的选项会从 setup 中提升到模块的作用域。因此,传入的选项不能引用在 setup 作用域中声明的局部变量。这样做会引起编译错误。但是,它可以引用导入的绑定,因为它们也在模块作用域内。
{{ message }}
中可以直接使用父组件传递的 props (可以省略
props .
) 需要通过
props.xx
来获取父组件传递过来的 propsemit子父传值的使用
i am father component
小结
内有效 ( defineProps defineEmits 这两个 API 都是只能在
中使用的编译器宏 )
中可以用