Using Vue.js and I am trying to add a conditional event handler to the keydown
event on an <input>
. I want to avoid adding the click handler at all if the condition is not met. I followed Evan You's suggestion:https://github.com/vuejs/vue/issues/7349#issuecomment-354937350
I'm getting an error saying Cannot read property '_wrapper' of null
for the following:
<input v-on: {
keydown: fieldData.fixedLength ? inputEnforceMaxlength : null,
}>
I also tried passing an empty object but got a different error saying: handler.apply is not a function
for the following:
<input v-on: {
keydown: fieldData.fixedLength ? inputEnforceMaxlength : {},
}>
Is this the proper way to add conditional event handlers or are there are other alternatives? Thanks!
You should be able to do something like this...
<input v-on="fieldData.fixedLength ? { keydown: inputEnforceMaxlength } : null">
Or you can just use a render()
function instead of a <template>
Using a render function ...
render(h) {
const data = {
on: {
blur: this.validate,
focus: this.showLabel,
},
};
if (this.fieldData.fixedLength) {
data.on.keydown = this.inputEnforceMaxlength;
}
if (this.fieldName === 'Phone') {
data.on.keypress = this.inputMaskTel;
}
return h('input', data);
}
If you need to use some events, that must go to the parent component, you can write smth like this:
<template>
<input v-on="customEvents" />
</template>
<script>
export default {
computed: {
customEvents: () => {
return [
...this.$listeners,
this.fieldData.fixedLength && { keydown: this.inputEnforceMaxlength }
];
}
}
}
</script>
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.