当另一个实例设置为true时,如何将组件的一个复选框实例设置为false



如何在vue.js中创建复选框组件,比如说(HTML表示(:

<v-switch></v-switch>
<v-switch></v-switch>

因此,当我创建两个这样的复选框时,如果第一个复选框设置为true,我想将另一个复选框更改为false,反之亦然。此外,它们也可能同时为假。

(我是vue.js的新手,我只想在现有的环境中添加它(。

存在的代码

Vue.component('v-switch', {
props: ['value', 'disabled', 'color'],
template: `
<div class="switch">
<label>
<input type="checkbox" :disabled="disabled" @change="emitChange()" v-model="data">
<span class="lever" :class="color_class"></span>
</label>
</div>`,
data: function () {
return {
data: this.value || '',
color_class: 'switch-col-' + (this.color || 'green')
};
},
methods: {
emitChange: function () {
var vm = this;
setTimeout(function () {
vm.$emit('change', vm.data);
});
}
},
watch: {
data: function () {
this.$emit('input', this.data);
},
value: function () {
this.data = this.value;
}
},
mounted: function () {
//this.data = this.value;
}
});

和HTML:

<v-input-wrap translate="newsletter" class="col-sm-1 col-12">
<v-switch v-model="contact_persons[index].newsletter"></v-switch>
</v-input-wrap>
<v-input-wrap translate="blacklist" class="col-sm-1 col-12">
<v-switch v-model="contact_persons[index].blacklist"></v-switch>
</v-input-wrap>

您应该从子组件接收发出的值,并将@change事件的方法处理程序添加到每个组件,当您检查一个组件时,另一个组件将被取消选中,最初它们是未选中的

Vue.component('v-switch', {
props: ['value', 'disabled', 'color'],
template: `
<div class="switch">
<label>
<input type="checkbox" :disabled="disabled" @change="emitChange" v-model="data" />
<span class="lever" :class="{'switch-col-green':value,'switch-col-red':!value}">{{value}}</span>
</label>
</div>`,
data: function() {
return {
data: this.value || false,
color_class: 'switch-col-' + (this.color || 'green')
};
},
methods: {
emitChange: function() {
var vm = this;
console.log(this.data)
vm.$emit('change', vm.data);
}
},
watch: {
data: function() {
this.$emit('input', this.data);
},
value: function() {
this.data = this.value;
}
},
mounted: function() {
//this.data = this.value;
}
});
// ignore the following two lines, they just disable warnings in "Run code snippet"
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data() {
return {
ch1: false,
ch2: false
}
},
methods: {
change1(v) {
this.ch1 = v;
this.ch1?this.ch2 = !this.ch1:this.ch2;
},
change2(v) {
this.ch2 = v;
this.ch2?this.ch1 = !this.ch2:this.ch1;
}
}
});
.switch-col-green{
color:green;
}
.switch-col-red{
color:red;
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app" class="container">
<v-switch :value="ch1" @change="change1"></v-switch>
<v-switch :value="ch2" @change="change2"></v-switch>
</div>

最新更新