Vue 中使用插槽

“插槽” 的概念还是挺重要的。在很多Vue 第三方插件 或 模块中,大量使用了插槽特性。

他的使用,首先,定义一个组件:

<body>
	<div id="root">
		<child></child>
	</div>
	<script>
		Vue.component("child",{
			template: "<div><p>hello</p></div>"
		})

		var vm = new Vue({
			el: "#root"
		})
	</script>

</body>

然后,子组件里希望展示父组件传递过来的内容:

	<div id="root">
		<child content="<p>say hi</p>"></child>
	</div>
	<script>
		Vue.component("child",{
			props: ["content"],
			template: "<div><p>hello</p>{{content}}</div>"
		})

		var vm = new Vue({
			el: "#root"
		})
	</script>

上面的代码得到的结果,不是我们期望的,因为会这样:

                        

那么就需要使用v-html 命令了:

	<div id="root">
		<child content="<p>say hi</p>"></child>
	</div>
	<script>
		Vue.component("child",{
			props: ["content"],
			template: `<div>
						 <p>hello</p>
						 <div v-html="this.content"></div>
						</div>`
		})

		var vm = new Vue({
			el: "#root"
		})
	</script>

这样子,显示起来是没问题的,但是dom 会在p 标签外包裹一层div 标签。

当子组件的一部分内容,是根据父组件传递过来的dom 进行显示的时候,请使用插槽 slot。

	<div id="root">
		<child>
			<p>say hi</p>
			<h1>Hi</h1>
		</child>
	</div>
	<script>
		Vue.component("child",{
			template: `<div>
						<p>hello</p>
						<slot></slot>
						</div>`
		})
		var vm = new Vue({
			el: "#root"
		})
	</script>

如上。slot 还可以定义默认值:

						<slot>默认内容</slot>

具名插槽(给插槽赋上名字):

	<div id="root">
		<body-content>
			<div class="header" slot="header">header</div>
			<div class="footer" slot="footer">footer</div>
		</body-content>
	</div>
	<script>
		Vue.component("body-content",{
			template: `<div>
						<slot name="header">h</slot>
						<div class="content">content</div>
						<slot name="footer">f</slot>
						</div>`
		})
		var vm = new Vue({
			el: "#root"
		})
	</script>

猜你喜欢

转载自blog.csdn.net/purple_lumpy/article/details/83098303