slot-插槽的基本使用-具名插槽的使用
为什么使用slot ?
slot翻译为插槽:
1.在生活中很多地方都有插槽,电脑的USB插槽,插板当中的电源插槽。
2.插槽的目的是让我们原来的设备具有更多的扩展性。
3.比如电脑的USB我们可以插入U盘、硬盘、手机、音响、键盘、鼠标等等。
组件的插槽:
1.最暗的插槽也是为了让我们封装的组件更加具有扩展性。
2.让使用者可以决定组件内部的一些内容到底展示什么。
栗子:移动网站中的导航栏:
1.移动开发中几乎每个页面都有导航栏。
2.导航栏我们必然会封装成一个插件,比如nav-bar组件。
3.一旦有了这个组件,我们就可以在多个页面中复用了。
如何封装这类组件呢? slot
1.它们有很多区别,但是也有很多共性。
2.如果,我们每一个单独去封装一个组件,显然不合适:比如每个页面都返回,这部分内容就要我们重复去封装。
3.但是,如果我们封装成一个,好像也不合理:有些左侧是菜单,有些是返回,有些是中间搜索,有些是文字等等。
如何封装何时呢?抽取共性, 保留不同
1.最好的封装方式就是将共性抽取到组件中,将不同暴露为插槽。
2.一旦我们预留了插槽,就可以让使用者根据自己的需求,决定插槽中插入什么内容。
3.是搜索框,还是文字,还是菜单,由调用者自己来决定。
1.插槽的基本使用:< slot >< /slot >
2.插槽的默认值: < slot > button </ slot >
3.如果有多个值,同时放入到组件中替换时,一起作为替换元素
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn></cpn>
<cpn><span>hello</span></cpn>
<cpn><i>hi</i></cpn>
<cpn><button>OK</button></cpn>
<cpn>
<span>Emma</span>
<p>我是p</p>
<div>我是div</div>
</cpn>
<cpn></cpn>
<cpn></cpn>
</div>
<template id="cpn">
<div>
<h2>我是组件</h2>
<p>我是组件,哈哈哈哈</p>
<slot><button>按钮</button></slot>
<!--<button>按钮</button>-->
</div>
</template>
<script src="../../vue.min.js"></script>
<script>
const app=new Vue({
el:'#app',
data:{
message:'hello',
},
components:{
cpn:{
template:'#cpn',
}
}
})
</script>
</body>
</html>
具名插槽
给插槽添加name
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn>
<span slot="left">gg</span>
<span slot="center">标题</span>
<span>右边</span>
<span>哈哈哈</span>
</cpn>
</div>
<template id="cpn">
<div>
<slot name="left"><span>左边</span></slot>
<slot name="center"><span>中间</span></slot>
<slot name="right"><button>取消</button></slot>
<slot><button>按钮</button></slot>
</div>
</template>
<script src="../../vue.min.js"></script>
<script>
const app=new Vue({
el:'#app',
data:{
message:'hello',
},
components:{
cpn:{
template:'#cpn',
}
}
})
</script>
</body>
</html>