首页 > Web开发 > 详细

[Mise] Focus an input field on button click with `x-ref` and the `$refs` property in Alpine JS

时间:2020-05-14 20:14:09      阅读:49      评论:0      收藏:0      [点我收藏+]

In this lesson, we learn how to retrieve a DOM element via the x-ref directive in Alpine JS, which gives us a reference to the element it is applied on. In our case, an input field.

We can then use the $refs object, and reach for the ref we need to target.

This allows us to trigger the focus state of the input field, with the .focus() method.

 

<div x-data="{name: ‘‘}">
  <label>Your name</label>
  <!-- ref to a dom node-->
  <input x-ref="nameInput" type="text" x-model="name">
  <p>Hi, my name is <span x-text="name || ‘_______________‘"></span>! ??</p>
   <!-- get ref and call the method-->
  <button @click="$refs.nameInput.focus()">set focus</button>
</div>

 

[Mise] Focus an input field on button click with `x-ref` and the `$refs` property in Alpine JS

原文:https://www.cnblogs.com/Answer1215/p/12890683.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!