自定義vue radio控制元件
阿新 • • 發佈:2019-02-06
如何使用vue自定義radio控制元件?
背景
原生瀏覽器的radio控制元件的樣式誰用誰知道,一個字醜! 所以今天要使用vue之間封裝一個美美噠的radio控制元件.
實現功能
- 自定義v-model,使元件之間資料能夠進行雙向繫結.
- 使用checked屬性預設選中radio
- 使用disabled屬性禁用radio
- 當用戶點選radio時觸發元件上繫結的change事件
程式碼實現
- 定義指令碼
<script>
export default {
name:'ui-radio',//radio元件名稱
model: {//自定義 v-model的 prop和event,這個定義的意思就是使用change事件更新model的值,以此來實時更新v-model的值
prop: 'model',
event: 'change'
},
props:{
value:{//radio的value屬性
type:[String,Number],
require:true
},
model:{//這裡的model指的是上面定義的v-model的prop
type:[String,Number],
require:true
},
checked:{//是否預設選中
type:Boolean,
default:false
},
disabled:{//是否禁用
type:Boolean,
default:false
}
},
mounted:function(){//當dom渲染完成,判斷元件是否預設選中
if(this.checked===true)
this.updateVal();
},
methods:{
updateVal:function(){//當用戶點選radio時,觸發change事件更新v-model
this.$emit('change',this.$refs.radio.value);
}
}
}
</script>
- 定義元件模板
<template>
<!--這裡設定了選中後的radio樣式類,和禁用後的樣式類-->
<label class="ui-radio" :class="{'checked':model==value,'disabled':disabled}">
<input type="radio" ref="radio" :value="value" @click="updateVal" :disabled="disabled">
</label>
</template>
- 定義樣式(樣式就不再細說了,可以在部落格底部開啟code sandbox 自己除錯)
<style>
.ui-radio{
width: 14px;
height: 14px;
border-radius: 50%;
border: 1px solid #4693fe;
display: inline-block;
position: relative;
}
.ui-radio.disabled{
border-color: #ccc;
}
.ui-radio::after{
content: '';
width: 10px;
height: 10px;
border-radius: 50%;
display: inline-block;
position: absolute;
left: 50%;
top: 50%;
margin: -5px 0 0 -5px;
background-color: #4693fe;
transition: all .5s ease;
opacity: 0;
transform: scale(0);
}
.ui-radio.disabled::after{
background-color: #ccc;
}
.ui-radio.checked::after {
opacity: 1;
transform: scale(1);
}
.ui-radio input[type=radio]{
opacity: 0;
margin: 0;
}
</style>
效果和示例程式碼
如果示例空白請稍等一會,等待載入完畢.