zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue.js:插槽的基本使用

VueJS 基本 插槽 使用
2023-09-27 14:22:47 时间

插槽的基本使用

  • 组件中的插槽
    • 组件的插槽也是为了让我们封装的组件具有拓展性
    • 让使用者可以决定组件内部的一些内容到底展示什么
  • 实例:
    • 移动开发过程中,每个页面的导航栏
    • 导航栏我们必须封装成一个插件
    • 有了插件我们多个页面可以共用
  • 封装组件–>插槽

完整代码笔记

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="author" content="xiaonaihu" />
		<meta name="generator" content="HBuilder X" />
		<title>插槽的基本使用</title>
		<script src="../../lib/vue.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<!-- 
			1.插槽的基本使用:<slot></slot>
			2.插槽的默认值:<slot><button></button></slot>
			3.如果有多个值,需要同时放入组件中进行替换时,一起作为替换元素
		 -->
		<div id="app">
			<cpn><button>按钮</button></cpn>
			<cpn><span>xiaonaihu</span></cpn>
			<cpn>
				<i>小奶虎</i>
				<div>xiaonaihu</div>
				<p>xiaonaigou</p>
			</cpn>
			<cpn><button>按钮</button></cpn>
			<cpn></cpn>
		</div>
		<template id="cpn">
			<div>
				<h2>我是组件</h2>
				<p>我是小奶虎~</p>
				<slot></slot>
				<!-- 如果大量需要使用 可以赋一个默认值 -->
				<!-- 使用组件的时候没有传入时默认使用该插槽 -->
				<slot><button>按钮</button></slot>
			</div>
			
		</template>
		<script type="text/javascript">
			// 组件的插槽是为了让我们封装的组件更加具有拓展性
			var app = new Vue({
				el: "#app",
				data:{
					message:"hello vue"
				},
				components: {
					cpn: {
						template:'#cpn'
					}
				}
			});
		</script>
	</body>
</html>