源码如下:
{{ inactiveText }}
{{ activeText }}
解析:
(1)组件的html结构
input标签被隐藏掉了,css部分代码如下:
.el-switch__input {
position: absolute;
width: 0;
height: 0;
opacity: 0;
margin: 0;
}
如果把上面的样式代码注释掉,如图所示:
通过 的checked属性来控制文字显示以及开关的状态切换。最外层包裹的div是为了能够通过点击文字也能切换开关状态。
(2)混入的 mixins: [Focus('input'), Migrating]
主要是migrating.js,该文件主要是用于开发环境下提示一些迁移或者即将修改的属性和方法的。
示例:我用的element-ui v2.4.9,我按下面这样写,off-text属性在我当前的版本中已经被改为inactive-text
当我运行之后在控制台输出:
所有迁移的属性在组件的getMigratingConfig()方法中:
getMigratingConfig() {
return {
props: {
'on-color': 'on-color is renamed to active-color.',
'off-color': 'off-color is renamed to inactive-color.',
'on-text': 'on-text is renamed to active-text.',
'off-text': 'off-text is renamed to inactive-text.',
'on-value': 'on-value is renamed to active-value.',
'off-value': 'off-value is renamed to inactive-value.',
'on-icon-class': 'on-icon-class is renamed to active-icon-class.',
'off-icon-class': 'off-icon-class is renamed to inactive-icon-class.'
}
};
}
(3)created方法
created() {
//如果用户传入的v-model的值既不是activeValue也不是inactiveValue时,将inactiveValue传递出去,开关处于关状态
if (!~[this.activeValue, this.inactiveValue].indexOf(this.value)) {
this.$emit('input', this.inactiveValue);
}
},
~代表按位非运算符,如果[this.activeValue, this.inactiveValue].indexOf(this.value)为-1,则按位非后变为0。
参考博文:https://juejin.im/post/5b861db0e51d4538aa1b5630
http://www.zhuyuntao.cn/2018/10/24/element-ui-focus-js和migrating.js文件源码学习