Alpine.js: 如何让ref元素可见并聚焦于点击?

Alpine.js: How to make ref element visible and focus on click?

当我按下 link“Hallo”时,我希望 link“Okay”可见且集中。但是,当我单击“Hallo”时,“Okay”link 将变得可见,但它没有聚焦。仅当我再次单击 link“确定”时才会聚焦。我怎样才能实现一键显示和聚焦 link?

  a:focus{
      color:yellow;
    }
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>
<div x-data="{open:false}">
  <a href="#" @click="open=true;$refs.foo.focus()" >Hallo</a>
  <div x-show="open">
    <a href="#" x-ref="foo">Okay</a>
  </div>
</div>

当你的JS执行时,foo元素还没有显示,所以它不能被聚焦。在聚焦之前,您需要等待它显示。 $nextTick 允许您这样做:

$nextTick is a magic property that allows you to only execute a given expression AFTER Alpine has made its reactive DOM updates. This is useful for times you want to interact with the DOM state AFTER it's reflected any data updates you've made.

a:focus{
  color:yellow;
}
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>
<div x-data="{open:false}">
  <a href="#" @click="open=true;$nextTick(() => { $refs.foo.focus(); });" >Hallo</a>
  <div x-show="open">
    <a href="#" x-ref="foo">Okay</a>
  </div>
</div>

Is it possible to pass $nextTick to a function and call it there? Or can I only call it inline?

您可以在 x-data 中添加 myMethod 属性,并通过 this:

访问所有内容

const appData = {
  open: false,
  myMethod() {
    this.open = true;
    this.$nextTick(() => { this.$refs.foo.focus(); });
  }
};
a:focus {
  color: yellow;
}
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js"></script>
<div x-data="appData">
  <a href="#" @click="myMethod">Hallo</a>
  <div x-show="open">
    <a href="#" x-ref="foo">Okay</a>
  </div>
</div>