一.为什么要进行组件的封装
因为代码里面有很多复用地方,可以将他封装一个组件,对组件进行复用,举个简单的例子,你在做移动端的时候tabbar,很多地方都会进行复用。
二.利用slot进行组件的封装
通过插槽实现对按钮的定制
<template>
<div class="">
<buttons>
<template v-slot:button1 v-slot:button2>
<!-- <div v-slot="number">{{ number }}</div> -->
<!-- 默认要放入的内容 -->
<p>1</p>
<button style="background: yellow">添加</button>
<button style="background: blue">删除</button>
</template>
<!-- 具名插槽的使用方法 -->
</buttons>
<buttons>
<template v-slot:button1 v-slot:button2>
<p>2</p>
<button style="background: orange">查看</button>
<button style="background: pink">看查</button>
</template>
</buttons>
<buttons>
<template v-slot:button1 v-slot:button2 v-slot="data">
<p>3</p>
<h1>{{ data }}</h1>
<button style="background: aqua">去除</button>
<button style="background: chocolate">加添</button>
</template>
</buttons>
</div>
<!-- 现在要实现不同颜色的定制 -->
<!-- 实现颜色不同的定制 -->
</template>
<script>
import buttons from "./components/tanchuang.vue";
export default {
components: {
buttons,
},
name: "",
methods: {},
};
</script>
<style scoped></style>
<template>
<div class="">
<!-- 1.封装的组件 -->
<div>
<input type="text" />
<!--2.默认要放入的内容 -->
<slot></slot>
<!-- 3.具名 -->
<slot name="button1"></slot>
<slot name="button2"></slot>
</div>
</div>
</template>
<script>
export default {
data() {
return {};
},
name: "",
methods: {},
};
</script>
<style scoped>
div {
width: 800px;
height: 100px;
background: pink;
display: flex;
}
input {
width: 700px;
height: 100px;
border-color: aqua;
}
</style>
图示:
默认插槽实现了内容的定制,具名插槽实现了不同按钮颜色的定制