v-model 在绑定modelValue
或者在input
标签中使用的时候其实和 SFC 差不多
import { defineComponent, ref } from "vue"; export default defineComponent({ name: "app", setup(props, ctx) { const num = ref(0); return () =>; }, });
当在组件中使用绑定自定义事件的时候和 SFC 就有了区别,比如绑定一个msg
,在 SFC 中直接v-model:msg
即可,而在 JSX 中则需要使用一个数组。我们直接看下面两个例子你就会明白,假如我们组件名叫ea_button
,这个组件发送了一个update:changeMsg
的方法,父组件的msg
变量需要接受update:changeMsg
函数传来的参数
SFC:
JSX:
先看下默认插槽,我们定义一个子组件 Child 接收一个默认插槽
import { defineComponent, ref } from "vue"; const Child = (props, { slots }) => { return{slots.default()}; }; export default defineComponent({ name: "app", setup(props, ctx) { const num = ref(0); return () =>默认插槽; }, });
如果想使用具名插槽则需要在父组件中传入一个对象,对象的 key 值就是插槽的名字
import { defineComponent, ref } from "vue"; //@ts-ignore const Child = (props, { slots }) => { return ( {slots.slotOne()} {slots.slotTwo()} {slots.slotThree()} ); }; export default defineComponent({ name: "app", setup(props, ctx) { const num = ref(0); return () => ( { { slotOne: () =>插槽1, slotTwo: () =>插槽2, slotThree: () =>插槽3, }} ); }, });
如果我们想在父组件的插槽内容中获取到子组件中的变量,此时便涉及到了作用域插槽。在 JSX 中我们可以在子组件调用默认插槽或者某个具名插槽的时候传入参数,如下面的插槽一为例
import { defineComponent, ref } from "vue"; //@ts-ignore const Child = (props, { slots }) => { const prama1 = "插槽1"; return ( {slots.slotOne(prama1)} {slots.slotTwo()} {slots.slotThree()} ); }; export default defineComponent({ name: "app", setup(props, ctx) { return () => ( { { slotOne: (pramas: string) =>{pramas}, slotTwo:插槽2, slotThree:插槽3, }} ); }, });
我们可以看到prama1=插槽1
是子组件中的变量,我们通过slots.slotOne(prama1)
将其传到了父组件的插槽内容中
关于 Vue3 中 JSX 的语法就介绍这么多,其实如果你熟悉 Vue 的 SFC 语法还是能很快上手 JSX 语法的,因为它们也就是写法上有一些区别,用法上还是基本一样的。至于选择哪一种写法还是取决于我们自己,我的建议是二者兼得,你可以根据实现不同的功能采用不同的写法。当然,如果你是一个团队项目,你还是乖乖听你领导的吧。
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者