I have this SwitchButton component in my Vue.js app that has a custom event 'toggle'. When clicking (switching) the button, the toggle event sets isEnabled to false or true. No problems with that but when I bind isEnabled in the parent component to the SwitchButton child component to set its initial value, it doesn't seem to work.
Code used in parent component (giving isEnabled true as initial value)
<SwitchButton v-model="distSwitch" :isEnabled="true">
<label slot="left">{{ $t('general.dealer') }}</label>
<label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>
SwitchButton component:
<template>
<div class="switch-button-control">
<div class="switch-button-label">
<slot name="left"></slot>
</div>
<div class="switch-button" :class="{'enabled': isEnabled}" @click="toggle">
<div class="button"></div>
</div>
<div class="switch-button-label">
<slot name="right"></slot>
</div>
</div>
</template>
<script>
export default {
name: 'SwitchButton',
model: {
prop: 'isEnabled',
event: 'toggle'
},
props: {
isEnabled: {
type: Boolean,
required: true
}
},
methods: {
toggle() {
this.$emit("toggle", !this.isEnabled);
}
},
created() {
/*eslint-disable no-console*/
console.log('isEnabled', this.isEnabled)
}
}
</script>
I expect the console.log in the created hook to output "isEnabled > true" but it outputs "false" instead
What am I missing here?
Since the value for the property isEnabled
is set by a hard codded true
, changing it from the child component won't work.
Initialising a data variable in parent component and set as property can help here.
Template:
<SwitchButton v-model="distSwitch" :isEnabled="isEnabled" @toggle="toggleIsEnabled">
<label slot="left">{{ $t('general.dealer') }}</label>
<label slot="right">{{ $t('general.wholesale') }}</label>
</SwitchButton>
Data:
data:()=>{
return {
isEnabled:true
}
}
Create a method in the methods
section:
toggleIsEnabled:function(value){
this.isEnabled = value;
}
The emitted value from SwitchButton
component using the custom event emitter toggle
will trigger the callback function toggleIsEnabled
in the parent component.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.