Vue入门(3)插槽

1.插槽

插槽,内置组件slot,作为承载分发内容的出口

先看一下下面的代码:声明一个child-component组件,如果现在我想在
<child-component></child-component>内放置一些内容,结果会是怎样?

<div id="app">
    <child-component></child-component>
</div>
<script>
    Vue.component('child-component',{
        template:`
            <div>Hello,World!</div>
        `
    })
    let vm = new Vue({
        el:'#app',
        data:{

        }
    })
</script>

<child-component>你好</child-component>

输出内容还是在组件中的内容Hello,World!,在 <child-component>内写的你好没起作用。

我们现在给组件增加一个插槽

Vue.component('child-component',{
    template:`
        <div>
        Hello,World!
        <slot></slot>
        </div>
    `
})

回到页面发现我们在<child-component></child-component>内写的你好起作用了!!!

没有插槽的情况下在组件标签内些一些内容是不起任何作用的,当我在组件中声明了slot元素后,在组件元素内写的内容就会跑到它这里了!

2.具名插槽

在组件中,我给插槽起个名字,一个名字叫"girl",一个名字叫"boy",还有一个不起名字。然后再<child-component></child-component>内,slot属性对应的内容都会和组件中name一一对应。而没有名字的,就是默认插槽!

<div id="app">
	<child-component>
		<h1 slot="girl">漂亮、购物、逛街</h1>
		<h2 slot="boy">帅气、才实</h2>
		<h3>我是一类人,我是默认的插槽</h3>
	</child-component>
</div>
<script>
	Vue.component('child-component',{
		template:`
			<div>
				<h4>这个世界不仅有男人和女人</h4>
				<slot name="girl"></slot>
				<div style="height:1px;background-color:red;"></div>
				<slot name="boy"></slot>
				<div style="height:1px;background-color:red;"></div>
				<slot></slot>
			</div>
		`
	})
	let vm = new Vue({
		el:'#app',
		data:{

		}
	})
</script>

猜你喜欢

转载自blog.csdn.net/weixin_36302575/article/details/87914282