简体   繁体   English

如何在 Vue.js 中正确添加条件事件绑定?

[英]How to properly add conditional event binding in Vue.js?

Using Vue.js and I am trying to add a conditional event handler to the keydown event on an <input> .使用 Vue.js,我正在尝试将条件事件处理程序添加到<input>上的keydown事件。 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我听从了 Evan You 的建议:https ://github.com/vuejs/vue/issues/7349#issuecomment-354937350

I'm getting an error saying Cannot read property '_wrapper' of null for the following:我收到一条错误消息,提示以下内容Cannot read property '_wrapper' of null

<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:我也尝试传递一个空对象,但得到一个不同的错误提示: 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>或者你可以只使用render()函数而不是<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM