Rails turbo_stream 如何实现以前 ujs 的效果?

wdrsam · September 05, 2022 · Last by amonlei replied at September 15, 2022 · 422 hits

例如一个请求过来,turbo_stream 来 render 了,就是执行了 turbo_stream 里的内容。现在想执行一段 js,比如过 3 秒关闭一个 div。在这个 turbo_stream 的思路下应该怎么实现这个效果呢?挺困惑的,是不是这种场景不该去使用 turbo_stream?

使用 stimulus 配合。

<turbo-stream action="append" target="messages">
  <template>
    <div id="message_1" data-controller="auto-hide" ><%= flash[:notice] %></div>
  </template>
</turbo-stream>

然后 stimulus:

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {

  // Search used: data-controller="auto-hide"

  // Search used: data-auto-hide-delay-value=
  static values = {
    delay: { type: Number, default: 10000 },
  }

  connect() {
    setTimeout(() => {
      this.element.classList.add("animate__fadeOut");
      setTimeout(() => {
        this.element.remove();
      }, this.delayValue);
    }, 2500);
  }
}
Reply to qichunren

感谢!一下茅塞顿开了

实在要用 ujs,把它开一下也没啥问题,可以和 turbo_stream 用在一起

Reply to hellonunam

是可以,但绑着 stimulus 用多爽呢!结构上来看 stimulus 结构上也要优雅一些。

stimulus 最大问题是在微信内置浏览器中无法执行

You need to Sign in before reply, if you don't have an account, please Sign up first.