前言
组件功能:把 el-switch 的值 true/false, 动态绑定输出为 0, 1
组件代码
封装el-switch组件,当el-switch的值为false,输出值为0;当el-switch的值为true,输出值为1;
<template>
<el-switch v-model="switchValue" @change="changeEvent">
</el-switch>
</template>
<script>
export default {
name: "Naruto-Switch",
props: {
value: {
type: String,
required: true
}
},
watch: {
value: {
immediate: true,
handler(val, oldVal) {
if (val && val !== oldVal) {
'0' === val ? this.switchValue = false : this.switchValue = true;
}
}
}
},
emits: ['update:value'],
data() {
return {
switchValue: false
}
},
methods: {
changeEvent(val) {
this.$emit(`update:value`, val ? '1' : '0');
}
}
}
</script>
main.js全局注册组件
import narutoSwitch from './components/Naruto-Switch.vue'
let app = createApp(App);
app.component('my-switch', narutoSwitch);
使用组件
<my-switch v-model:value="item.isPrimary"/>
vue3.0官方v-model语法解释
https://v3.cn.vuejs.org/guide/migration/v-model.html#_2-x-%E8%AF%AD%E6%B3%95