【问题标题】:VueJS trigger an event when a field is in focus当字段处于焦点时,VueJS 会触发一个事件
【发布时间】:2019-02-08 08:23:09
【问题描述】:

我有一个 VueJS 的密码更改页面,我只想在用户单击新密码字段时查看密码策略。 问题是我找不到页面是否在焦点上..

<b-row>
  <b-col>
    <b-form-group id="newPasswrd" label="New Password" :state="statePassword">
      <b-input-group>
        <b-form-input id="newPassword" v-model="passwords.newPassword" ref="newPassword" placeholder="Passwort" type="password" maxlength="60" />
        <p class="password-description"  >Must be at least 8 characters and contain at least two of the following: Upper case, Lower case, special characters or numbers</p>            
      </b-input-group>
    </b-form-group>
  </b-col>
</b-row>

这就是我在页面脚本部分中用于测试的内容:

      if (this.$refs.newPassword.focus() == true) console.log("focus");

我的计划是最终将此行放入计算中并为其附加一个布尔值以查看/隐藏字段下方的文本,具体取决于它是否处于焦点。 发生的情况是,当我触发写入此条件的方法时,我在控制台中什么也得不到,但是焦点却转到了字段上,这不是我想要的。 如果该字段处于焦点位置,我应该怎么做才能获得布尔值?

【问题讨论】:

标签: javascript vue.js frontend


【解决方案1】:

您可以创建自定义指令

Sample from official vuejs docs

Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})

【讨论】:

  • 问题是检测焦点不是设置它。
  • 这只是创建指令的示例,您可以随意更改它
  • 这是一个很好的第一步,但仍然不能解决问题;)
【解决方案2】:

你试过只用 css 吗?

如果您不必支持 IE11/Edge:

b-input-group:focus-within>p {
    display: block;
}

如果你必须支持 IE11/Edge:

input:focus + p {
    display: block;
}

我还建议添加类而不是准系统元素。

【讨论】:

    【解决方案3】:

    使用v-onnative 修饰符进行绑定:

    v-on:focus.native="onFocus"
    

    From a Core Member

    Binding Native Events to Components

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多