组件封装
封装
<template>
<div class="box">
<button class="btn">{{ des }}</button>
</div>
</template>
<script>
export default {
props: {
des: {
type: String
}
},
methods: {}
}
</script>
<style lang="less" scoped>
.btn {
width: 60px;
height: 60px;
border: 1px solid #fff;
border-radius: 50%;
color: #fff;
font-size: 12px;
text-align: center;
background-color: #2b85e0;
}
</style>
使用
1.使用组件,并绑定点击事件
<btn :des="msg" @click.native="BtnClicked1"></btn>
export default {
components: {
checkBoxs: () => import('../components/checkbox.vue'),
btn: () => import('../components/selfComponent.vue')
},
data() {
return {
msg: '组件'
}
},
methods: {
BtnClicked1() {
console.log(555555)
}
}
}
点击按钮之后,打印出555555
通过属性绑定给组件传递想要显示的内容,而且给组件绑定了点击事件,注意给组件绑定原生事件的使用需要使用native事件修饰符,不然不会生效
2.在另一个页面中也引入改组件,修改按钮样式且绑定点击事件:
<btn :des="info" @click.native="btnClicked2" class="btnBgc"></btn>
export default {
components: {
btn: () => import('../components/selfComponent.vue')
},
data() {
return {
msg: '组件'
}
},
methods: {
BtnClicked2() {
console.log(66666)
}
}
}
<style lang="less" scoped>
/deep/.btnBgc button {
background-color: red;
}
</style>
点击打印66666
我这里修改了组件中按钮的背景颜色,但是第一个使用例子中的按钮颜色并没有受到影响
想要在父组件中改变子组件中的样式,需要使用 /deep/ ,这样不仅不会造成要是污染,也能修改子组件样式
从上面的使用例子可以看到,不同文件使用封装的组件,他们是相互独立的;
颜色并没有受到影响
想要在父组件中改变子组件中的样式,需要使用 /deep/ ,这样不仅不会造成要是污染,也能修改子组件样式
从上面的使用例子可以看到,不同文件使用封装的组件,他们是相互独立的;
封装好的组件可以重复使用,也方便统一修改