前言
相信在座的各位小伙伴肯定都都使用过类似element的样式库,
只要修改其中按钮type属性就可以改变按钮的样式,在接下来的内容我们就可以实现这个效果。
- 我们要定义一个组件来接受父类组件的传值 并渲染出一个按钮
// button.vue
<script>
export default {
props:{
// 接受父组件的传值
type:{
type:String,
default:'normal'
},
text:{
type:String,
default:'normal'
}
},
render(h){
// h=> createElement
return h('button',{
//class:v-bind
class:{
btn:true,
'btn-success':this.type==='success',
'btn-error':this.type==='error',
'btn-warning':this.type==='warning',
'normal':!this.type
},
// doms属性
domProps:{
innerText:this.text || '默认文字'
},
//传事件
on:{}
})
}
}
</script>
<style scoped>
.btn{
width: 100px;
height: 40px;
color:#fff;
transition: all .3s;
}
.btn-success{
background: green;
}
.btn-error{
background: red;
}
.btn-warning{
background: orange;
}
.normal{
background-color: purple;
}
</style>
在组件中接受父类的传值,通过render函数来判断和添加当中的样式
- 其中h()函数类似于js中的creatElment()
- 在当中选择自己传的值并进行判断
2.父类调用这个组件并传值。
<template>
<Button :type=type :text=text />
</template>
<script>
import Button from '@/components/button'
export default {
name:'interview',
data(){
return{
type:'error',
text:'失败按钮'
}
},
components:{
Button
}
}
</script>
3.结果