
就和小时候这个游戏机一样,插黄色游戏卡的地方就是插槽。而黄色游戏卡就是插槽内容。
普通插槽
在vue中,插槽用于父组件像子组件分发内容。下面是一个最简单的插槽写法:
父组件

子组件

其中slot
元素就是子组件的预备插槽(相当于插游戏卡得区域),而父组件里的"我是内容..."就相当于游戏卡了,如果没有slot
元素那么内容区域就无法显示。
具名插槽
当组件的功能过于复杂时,可能需要像子组件添加多个插槽,这个时候就像手柄插口和游戏卡插口是一样的,不可能把手柄插口插到游戏卡插槽内。所以需要用到具名插槽。
父组件

子组件

如上图,子组件内的slot元素,我们通过属性name
给他绑定好了手柄和游戏卡的插槽名字。插槽有了名字以后,那我们得找到游戏卡和手柄,这个时候父组件就需要通过v-slot
去给内容命名,如游戏卡v-slot:gameCard
。
v-slot简写
当然v-slot
我们看上去确实名字长了一些,像vue的其他命令一样,v-slot
也有一个缩写“#”,修改以后我们的父组件即

需要注意的是,在vue的2.6.0版本之后,v-slot命令只能用在template元素上。
作用域插槽
当我们插入游戏卡后,我们会选择我们喜欢的游戏,这个时候就得访问具体的游戏内容。在vue中,我们有时候需要父组件访问子组件内变量时。我们在子组件中的slot
元素上对变量进行属性绑定(他的专业名称叫插槽prop
),之后父组件上通过带值得v-slot定义插槽prop的名字。
父组件

子组件

网友评论