开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情
❤ 从0到1封装自己的vue组件
1、vue组件
组件(component)是vue.js最强大的功能之一,可以实现功能的复用,以及对其他逻辑的解耦。但经过一段时间的使用,不知不觉就将组件当成了减少业务代码长度,展现代码结构的一种工具,并没有做到可复用,发挥组件的长处。
2、组件
对于一个独立的组件来说,props是用来为组件内部注入核心的内容;
$emit用来使这个独立的组件通过逻辑来融入其他组件中。
举个具体点的例子,假如你要建一个房子,窗户是要封装的一个独立组件,props指的就是根据整个房子的外形你可以给窗户设置一些你想要的且符合房子风格的窗户颜色,样式等;
而$emit的作用则是让窗户能够和房子完美契合。
根目录srx下新建一个components,用于放我们之后开发的组件的源码
封装好一个组件,一定要熟练掌握: 父组件 —> 子组件传值(props) 子组件 —> 父组件传值($emit) 以及插槽(slot)
3、先从一个按钮组件开始了解组件的封装
思路:
通过改变按钮类名来改变自定义组件按钮样式【非常之简单】
- 文件目录如下一目了然
❤ 【1】在components(组件目录下) 下新建一个Spebutton 文件夹,文件夹下建立一个index.vue(组件默认先从index.vue里面拿内容)
index.vue里面包含三部分:
- 按钮容器
<template>
<div>
<button :class="`my-btn btn-${type}`"><slot></slot></button>
</div>
</template>
- js部分 组件的名称、组件的props传值(类型为字符串 和 默认为Button)
<script>
export default {
name: "Spebutton", //组件名称 Spebutton 必须的
props: {
type: {
type: String,
default: "Button",
},
},
}
</script>
三个按钮样式部分
<style>
.btn-primary1{
background: #1890FF;
color: #fff;
border: 0px;
padding:5px 10px;
border-radius: 2px;
margin: 5px;
}
.btn-primary2{
background: #3d4145;
color: #fff;
border: 0px;
padding:5px 10px;
border-radius: 2px;
margin: 5px;
}
.btn-primary3{
background:#285d0d;
color: #fff;
border: 0px;
padding:5px 10px;
border-radius: 2px;
margin: 5px;
}
</style>
❤ 【2】在main.js 里面全局注册和使用
import Spebutton from '@/components/Spebutton' // 组件路径
Vue.component(Spebutton.name,Spebutton)
【不可忽略】在组件里头写上 components: {Spebutton },
❤ 【3】在想要使用的位置直接写上三个按钮的类型
<Spebutton type="primary1" class="notes">按钮primary1</Spebutton>
<Spebutton type="primary2" class="notes">按钮primary2</Spebutton>
<Spebutton type="primary3" class="notes">按钮primary3</Spebutton>
最后效果如下
【4】补充:当然,有时候我们也可能只是局部使用
这时候第【2】就改成在需要的页面里面直接引入组件
包含三部分:引入组件路径、注册组件、使用组件
import Spebutton from '@/components/Spebutton' // 组件路径
components: {Spebutton},
<Spebutton type="primary1" class="notes">按钮primary1</Spebutton>
<Spebutton type="primary2" class="notes">按钮primary2</Spebutton>
<Spebutton type="primary3" class="notes">按钮primary3</Spebutton>
完整部分如下:
附带代码index.vue 可直接复制检测:
<template>
<div class="app">
<Spebutton type="primary1" class="notes">按钮primary1</Spebutton>
<Spebutton type="primary2" class="notes">按钮primary2</Spebutton>
<Spebutton type="primary3" class="notes">按钮primary3</Spebutton>
</div>
</template>
<script>
import Spebutton from '@/components/Spebutton' // 组件路径
export default {
name: "index",
components: {Spebutton},
data(){
return{}
},
methods:{},
}
</script>
效果相同: