在使用组件时,组件开始标签和结束标签的内容会被忽视,如下代码
I want to be shown
这里my-com开始标签和结束标签间的内容不会显示出来,整个标签都被模板覆盖了,如果要在html中传入开始标签和结束标签之间的内容的话,就可以使用插槽。
插槽通过
I want to be shown
在页面中最终就会渲染为
this is the template I want to be shown
可以看到标签间的内容已经被渲染到原来的
标签间的内容会以html的方式解析出来,即是说可以在标签里面放html结构。
I am a span
喧嚷到页面后为
this is the template
I am a span
如果要在标签内没内容时传入一个默认值,那么直接在模板中的
I want to be shown
在页面中渲染为
this is the template
I want to be shown
this is the template
I am the default value
如果要在模板的不同位置插入不同的内容,就可以使用具名插槽,为每个位置指定具体的名称,分别插入不同的内容。
具名插槽在组件标签中使用template来包裹插槽的内容,并使用v-slot指明插槽的名称,然后在模板中的
I am the first
I am the second
I am the third
在页面中渲染为
I am the first
I am the second
I am the third
如果有一个template没有指明使用插槽名称,则默认使用defult作为名称
I am the first
I am the second
I am the third
I don't have v-slot
页面中渲染为
I am the first
I am the second
I am the third
I don't have v-slot
v-slot也可以绑定data中变量对应的内容,只要在v-slot后面的内容添加[]即可。
I am the first
I am the second
I am the third
在页面中渲染为
I am the first
I am the second
I am the third
v-slot和v-bind,v-on一样,有自己的缩写"#"。使用缩写与原来渲染出来的结果是相同的。
I am the first
I am the second
I am the third
插槽可以使用其组件所在的父组件的data,但不可以直接使用其组件的data
{{childStr}}
{{parentStr}}
要使用其组件中的data,可以在其父作用域中设置一个插槽prop,在组件的模板中将组件的data中的值作为slot的特性绑定到父作用域中。设置插槽prop可以使用v-slot(#),与上面指明哪一个slot使用“:”不一样,这里使用的是“=”。
{{slotProps.childStr}}
在设置插槽prop时,可以采用解构插槽的方法,这样会更为便利,减少了prop名称的设置
{{childStr}}
使用解构插槽时,可以设置默认值,在没有该值时使用默认值,直接使用=即可。
{{childStr}}
页面最后渲染为
default value
可以看到最后是使用了默认值。