组件嵌套元素

一般定义组件,组件内不会再嵌套其他元素标签,如下所示:

<my-component :item="item">
	<p>我是嵌套标签</p>
</my-component>

此时<p>元素标签并不会渲染出来。当然,正常情况下也不会有这种需求,因为如果你需要显示<p>标签,只要写入到<my-component>组件内即可。那有个疑问就是既然可以往组件内传参,那可不可以往组件内传递元素标签呢?这就意味着子组件的元素标签结构由父组件来决定。答案是可以的,这就是组件嵌套元素。

组件嵌套元素:在子组件中使用<slot>标签来替换父组件嵌入的标签,demo如下:

<body>
	<div id="app">
		<!-- slot为子组件的嵌套位置 -->
		<my-component :item="item">
			<p slot="slot1">我是嵌套标签,位置位于模板的slot元素下</p>
		</my-component>
	</div>
</body>

<script type="text/x-template" id="pid">
	<div>
		<label>{{item}}</label>
		<slot name="slot1">(我是slot1,只有在没有要分发的内容时才会显示这句话)</slot>
		<slot name="slot2">(我是slot2,只有在没有要分发的内容时才会显示这句话)</slot>
	</div>
</script>

<script>
	Vue.component("my-component", {
		props: ["item"], //第三方传参
		template: '#pid',
		data: function() {
			return {}
		}
	});

	var vue = new Vue({
		el: "#app",
		data: {
			item: "slot嵌套标签测试:"
		}
	});
</script>

运行结果:

 

 

导入.html文件作为模板

正常情况下,使用直接引用vue.js文件的方式,定义模板都使用<script type="text/x-template" id="pid"></script>来定义,更加方便的写法是直接通过文本写到template中。但是这都有一定的局限性,如在不同页面,以上的模板定义方法均不可以实现模板共享。此时,需要将模板写到一个独立的文件中,通过导入实现模板共享。

我们新建一个com.html文件,这个文件作为模板,代码如下:

<p>我是导入模板    自身参数:{{a}}|外部入参:{{b}}</p>

导入com.html我们需要借助jquery.js,代码如下:

<html>

	<head>
		<meta charset="utf-8" />
		<title></title>
		<script type="text/javascript" src="../js/libs/vue/2.4.2/vue.js"></script>
		<script type="text/javascript" src="../js/libs/jquery/jquery-1.11.3.js"></script>
	</head>

	<body>
		<div id="app">
			<hello-world :b="parame"></hello-world>
		</div>
	</body>

	<script>
		Vue.component('hello-world', function(resolve, reject) {
			$.get("./../xtemplate/com.html").then(function(res) {
				resolve({
					template: res,
					props: ["b"],
					data: function() {
						return {
							a: "a"
						}
					}
				})
			});
		});

		var vue = new Vue({
			el: "#app",
			data: {
				parame: "b"
			},
			methods: {},
			filters: {},
			computed: {},
			components: {},
			watch: {}
		});
	</script>

</html>

运行结果:

(贴士)如果使用es6通过import导入文件,会更加规范和便捷。

Logo

前往低代码交流专区

更多推荐