组件(第一种方案)
<script>
import {
Switch } from 'ant-design-vue'
export default {
name: 'GSwitch',
model: {
prop: 'checked',
event: 'change',
},
props: {
// 继承原生switch的props
...Switch.props,
checked: {
type: [Number, String, Boolean],
},
activeValue: {
//开启时的值
type: [Number, String, Boolean],
default: 1,
},
inactiveValue: {
//关闭时的值
type: [Number, String, Boolean],
default: 0,
},
},
computed: {
value() {
return this.checked === this.activeValue;
},
},
methods: {
onChange(event) {
this.$emit('change', event ? this.activeValue : this.inactiveValue);
},
onBlur(event) {
this.$emit('blur', event ? this.activeValue : this.inactiveValue);
},
},
render() {
return (
<Switch
onChange={
this.onChange}
onBlur={
this.onBlur}
// 传入修改后的props,和继承原生的scopedSlots
{
...{
props: {
...this.$props, checked: this.value },
scopedSlots: {
...this.$scopedSlots },
}}
></Switch>
)
},
}
</script>
注册
//全局使用 --文件路径自己修改
import GSwitch from "@/components/GSwitch/index.vue"
Vue.component(GSwitch.name,GSwitch)
//单文件
import GSwitch from '@/components/GSwitch'
components: {
GSwitch
}
使用
//默认1或0
<g-switch v-model="isSwtich" @change="onChange" />
//自定义
<g-switch v-model="isSwtich2" :active-value="100" :inative-value="-100" @change="onChange" />
methods: {
onChange(event) {
console.log(event)
}
}
组件(第二种方案)
<script>
import {
Switch } from 'ant-design-vue'
export default {
name: 'GSwitch',
model: {
prop: 'checked',
event: 'change',
},
props: {
// 继承原生switch的props
...Switch.props,
checked: {
type: [Number, String, Boolean],
},
activeValue: {
//开启时的值
type: [Number, String, Boolean],
default: 1,
},
inactiveValue: {
//关闭时的值
type: [Number, String, Boolean],
default: 0,
},
},
computed: {
value() {
this.$emit('change', event ? this.activeValue : this.inactiveValue);
return this.checked === this.activeValue;
},
},
render() {
return (
<Switch
on={
this.$listeners}
// 传入修改后的props,和继承原生的scopedSlots
{
...{
props: {
...this.$props, checked: this.value },
scopedSlots: {
...this.$scopedSlots },
}}
></Switch>
)
},
}
</script>
使用方式一致,第二种因为采用计算属性与on={this.$listeners},这样做会更加的灵活,且不用去重新实现组件的原生方法,但由于计算属性value会根据this.checked的改变而改变,会导致$emit及onChange多次调用**(暂无解决方案,如果有能解决的大佬请评论指点)**
防止多次调用onChange(临时解决)
<g-switch v-model="isSwtich" @change="onChange" />
methods: {
onChange(event)
if(typeof event === 'boolean'){
console.log(event)
}
}
}