switch
組件是用來表示對立關系的切換的。
生命周期
mounted
mounted() {
if (this.width === 0) { // 如果沒有傳 width
this.coreWidth = this.hasText ? 58 : 46; // 有文字的時候是 58px, 沒有文字則是 46px
}
this.handleButtonTransform(); // 移動按鈕
if (this.onColor || this.offColor) { // 如果設置了顏色
this.setBackgroundColor();
}
}
handleButtonTransform
這是用來處理按鈕的位移的方法。
methods: {
handleButtonTransform() {
// 根據開關移動圓點
this.buttonStyle.transform = this.value ? `translate(${ this.coreWidth - 20 }px, 2px)` : 'translate(2px, 2px)';
},
}
setBackgroundColor
這是用來改變開關顏色的。
methods: {
setBackgroundColor() {
// 根據開關設置顏色
let newColor = this.value ? this.onColor : this.offColor;
// 改變邊框和背景色
this.$refs.core.style.borderColor = newColor;
this.$refs.core.style.backgroundColor = newColor;
}
}
label
最外面是label
,上面會根據是否禁用以及是否有文字來設置不同的類名。
<label
class="el-switch"
:class="{
'is-disabled': disabled,
'el-switch--wide': hasText
}">
</label>
hasText
只要傳入了on-text
或者off-text
就表明有文字。
computed: {
hasText() {
return this.onText || this.offText;
},
}
mask
暫時沒發現遮罩的作用。
<div class="el-switch__mask" v-show="disabled"></div>
模擬原生input
<input
class="el-switch__input"
type="checkbox"
@change="handleChange"
v-model="_value"
:name="name"
:disabled="disabled">
handleChange
處理change
事件。
methods: {
handleChange(event) {
this.$emit('change', event.currentTarget.checked); // 派發 change 事件
},
}
_value
用來保存開關的情況,通過input
事件來使用讓父級改變value
,從而進而改變get
獲得的值。
computed: {
_value: {
get() {
return this.value;
},
set(val) {
this.$emit('input', val);
}
}
}
核心部分
這一部分是用戶真正接觸的開關部分。
<span class="el-switch__core" ref="core" :style="{ 'width': coreWidth + 'px' }">
<span class="el-switch__button" :style="buttonStyle"></span>
</span>
其中寬度用了coreWidth
,而buttonStyle
中目前只設置了transform
。
ON 標簽
這一部分是用來實現ON
標簽的。
<transition name="label-fade">
<div
class="el-switch__label el-switch__label--left"
v-show="value"
:style="{ 'width': coreWidth + 'px' }">
<i :class="[onIconClass]" v-if="onIconClass"></i>
<span v-if="!onIconClass && onText">{{ onText }}</span>
</div>
</transition>
label-fade
只是簡單的改變了透明度。
& .label-fade-enter,
& .label-fade-leave-active {
opacity: 0;
}
onIconClass
這是用來設置on
的時候顯示的圖標的,如果設置了這個就不會再顯示文字。
props: {
onIconClass: {
type: String,
default: ''
},
}
OFF 標簽
這與ON
類似,不再進行細致分析。
<transition name="label-fade">
<div
class="el-switch__label el-switch__label--right"
v-show="!value"
:style="{ 'width': coreWidth + 'px' }">
<i :class="[offIconClass]" v-if="offIconClass"></i>
<span v-if="!offIconClass && offText">{{ offText }}</span>
</div>
</transition>