vue插槽与具名插槽

  • 通过 slot 实现,如果没有定义name属性则就是存在slot就显示
  • 如果设置name属性的值,则就根据对应的name属展示。

1 无name属性值的案例

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="app">
			<num>
				<p>嵌套1</p>
				<p>嵌套2</p>
			</num>
		</div>
		<script type="text/javascript">
			const num = {
				template: `<div>
				<slot></slot>
				<h3>你好</h3>
				<slot></slot>
				</div>`,
			}


			new Vue({
				el: "#app",
				components: {
					num
				}
			})
		</script>


	</body>
</html>

2 设置name属性的slot
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			.modal {
				position: absolute;
				left: 0;
				right: 0;
				top: 0;
				bottom: 0;
				margin: auto;
				background-color: rgba(0, 0, 0, 0.3);
			}

			.modal-content {
				width: 300px;
				height: 260px;
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
				background-color: #fff;
				border-radius: 20px;
				overflow: hidden;
				
			}

			.modal-head {
				position: relative;
				height: 44px;
				background-color: #f0f0f0;
				line-height: 44px;
				padding: 0 15px;
			}
            
			.modal-head .close {
				position: absolute;
				top: 0;
				right: 0;
				height: 44px;
				line-height: 44px;
				text-align: center;
				width: 44px;
				color: orangered;
				cursor: pointer;

			}
			
			.modal-body{
				margin: 15px;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<h1>写一个弹出框</h1>
			<modal :visible="showModal" @update="showModal=$event;">
				<p slot="tiltle">我是标题</p>
				<div slot="content">
					<input type="text" placeholder="用户名" />
					<input type="password" placeholder="密码" />
				</div>
			</modal>
			<!-- 存入属性visible 为父组件的showMoal值的默认为false -->
			<button type="button" @click="showModal=true">弹出</button>
		</div>
		<script type="text/javascript">
			const modal = {
				template: `
				<div class="modal" v-if="visible">
				<div class="modal-content">
					<div class="modal-head">
						<slot name="tiltle"></slot>
						<span class="close" @click="$emit('update',false)">X</span>
					</div>
					<div class="modal-body">
						<slot name="content"></slot>
						<br>
						<button>确定</button>
					</div>
				</div>
			</div>`,
				props: {
					"visible": {
						type: Boolean,
						default: false,
						//接收父组件传入的值
						//组件的显示与隐藏有visible来控制
					}
				}
			}



			new Vue({
				el: "#app",
				components: {
					modal
				},
				data: {
					showModal: false,

				}
			})
		</script>


	</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40994735/article/details/108343791
今日推荐