前言
之前一直用的是elementui的radio,用的时候挺好用也挺简单的,直到最近工作中要自己封装一个,才发现这小东西也挺磨人的,于是自己在动手写一个的时候才发现原来自己还有这么多知识点没搞清楚
原始radio
原始的单选框直接将input的type设置为radio,但是样式却改不了
<input type="radio" />
但需要的样式必须是这样的
?废话不多说,上代码
<template>
<span class="radioList radioLink">
<span class="radioArea">
<label>
<input type="radio"
:value="label"
class="radioInput"
v-model="model"
:disabled="disabled">
<!-- 定义里面的点 -->
<span class="radioSelect"></span>
<span :class="[label === value ? 'character' : 'characterNo']">
<!-- 定义插槽 用来存放文字 -->
<slot></slot>
</span>
</label>
</span>
</span>
</template>
<script>
export default {
name: 'radio2',
data() {
return {}
},
props: {
// 接收v-model
//vue 再父子组件传值时,除了传统的父组件 :属性去传值外,还可以使用 父组件v-model传值,子组件props['value']接收,
label: {
type: [String, Number, Boolean],
default: '',
},
value: {
type: [String, Number, Boolean],
default: '',
},
disabled: {
type: Boolean,
default: false,
},
},
created() {},
methods: {},
computed: {
model: {
get() {
return this.label === this.value ? this.label : this.value
},
set(val) {
this.$emit('input', val)
},
},
},
watch: {},
}
</script>
<style scoped>
.radioLink {
box-sizing: border-box;
color: inherit;
min-height: 40px;
overflow: hidden;
position: relative;
text-decoration: none;
}
.character {
color: #000;
margin-left: 5px;
}
.characterNo {
margin-left: 5px;
}
.radioList {
height: 0.96rem;
line-height: 0.96rem;
width: 100%;
padding: 0rem 0.2rem;
box-sizing: border-box;
}
.radioArea,
.radioArea label {
cursor: pointer;
height: 0.96rem;
width: 100%;
margin-left: 5px;
}
.radioInput {
color: #ccc;
display: none;
}
.radioSelect {
box-sizing: border-box;
display: inline-block;
background-color: #fff;
border-radius: 100%;
border: 1px solid #ccc;
position: relative;
width: 20px;
height: 20px;
vertical-align: middle;
}
.radioInput:checked + .radioSelect {
background-color: #fff;
border-color: #fff;
border: 1px solid #000;
}
.radioInput:checked + .radioSelect::after {
background-color: #000;
-webkit-transform: scale(1);
transform: scale(1);
}
.radioSelect::after {
content: ' ';
border-radius: 100%;
top: 5px;
left: 5px;
position: absolute;
width: 8px;
height: 8px;
-webkit-transition: -webkit-transform 0.2s;
transition: -webkit-transform 0.2s;
transition: transform 0.2s;
transition: transform 0.2s, -webkit-transform 0.2s;
-webkit-transform: scale(0);
transform: scale(0);
}
</style>
在需要使用的组件中使用,最后得出的结果是
?
|