MySwitchView vue2组件
<template>
<div>
<el-switch
v-model="newValue"
:active-color="actColor"
:active-value="actValue"
:active-text="actText"
:inactive-color="inaColor"
:inactive-value="inaValue"
:inactive-text="inaText"
class="switchBox"
:style="{ width: styleWidth + 'px' }"
@change="switchChange"
/>
</div>
</template>
<script>
export default {
props: {
value: {
type: [String, Number, Boolean],
default: '1'
},
actValue: {
type: [String, Number, Boolean],
default: '1'
},
inaValue: {
type: [String, Number, Boolean],
default: '2'
},
actColor: {
type: String,
default: '#13ce66'
},
inaColor: {
type: String,
default: '#C0CCDA'
},
actText: {
type: String,
default: '开启'
},
inaText: {
type: String,
default: '关闭'
}
},
data() {
return {
newValue: this.value
}
},
computed: {
styleWidth() {
const maxLeng = this.actText.length >= this.inaText.length ? this.actText.length : this.inaText.length
return maxLeng * 10 + 45
}
},
watch: {
value: {
handler(newV) {
this.newValue = newV
},
immediate: true
}
},
methods: {
switchChange(vals) {
this.$emit('update:value', this.newValue)
this.$emit('change', this.newValue)
}
}
}
</script>
<style lang='scss' scoped>
/deep/.switchBox {
height: 29px;
position: relative;
.el-switch__label {
display: none;
}
.is-active {
display: block;
}
.el-switch__label--left {
position: absolute;
right: 10px;
z-index: 9;
color: white;
margin: 0;
}
.el-switch__label--right {
position: absolute;
left: 8px;
z-index: 9;
color: white;
margin: 0;
}
.el-switch__core {
width: 100% !important;
height: 27px;
border-radius: 16px;
}
.el-switch__core:after {
top: 2px;
width: 21px;
height: 21px;
}
}
/deep/ .switchBox.is-checked .el-switch__core::after {
width: 21px;
height: 21px;
margin-left: -23px !important;
}
</style>
父组件使用
<el-table-column
prop="is_top"
label="是否置顶"
width="90"
>
<template slot-scope="scope">
<MySwitchView
v-model="scope.row.is_top"
:value.sync="scope.row.is_top"
act-value="1"
act-text="开 "
act-color="#409eff"
ina-value="-1"
ina-text="关"
@change="MySwitchFunc($event, scope.row)" />
</template>
</el-table-column>
import MySwitchView from '@/components/mySwitchView.vue'
// 开启/关闭开关
MySwitchFunc(vals, row) {
audit.studentsDiscussionTop({
id: row.id,
}).then(res => {
if (res.code === 1) {
this.$common.notifySuccess(res.data)
}else{
this.$common.notifyError(res.message)
}
})
},