简体   繁体   中英

Stimulus.js way to load a partial?

We are investigating Stimulus.js for use with our Rails6 app and keep hitting conceptual walls in moving our thinking from jQuery to Stimulus.

For example:

On one part of the page we have a button and when that button is clicked we want to load content into a div on another part of the page. In jQuery this is simple - respond to click event, load in the part from the rails backend into that div.

In Stimulus, how to do this? It looks like everything needs to be in one big controller so that the button can see the 'target div'. So essentially we are writing 'page' controllers, which seems a lot of overhead. Also, it messes up the way we are breaking down the page into partials because now those partials need to share a Stimulus controller.

You definitely don't need to be writing 'page' controllers. The idea is that you write smaller controllers for interactive elements. If you post more about your use case perhaps we can help you split apart your controllers. You are correct though that the controller's element must contain any element registered as a target. Just remember you can access elements outside that context (eg in a completely different part of the page) using regular Javascript (in other words document.getElementById can give you access just as easily as using Stimulus targets)

To answer your question though, you can do something like this:

  show() {
      fetch("/path/to/partial")
        .then((res) => res.text())
        .then((html) => {
          const fragment = document
            .createRange()
            .createContextualFragment(html);

          this.element.appendChild(fragment);
          // OR document.getElementById("testy_element").appendChild(fragment)
        });
     
  }

What this does is fetch an HTML response from the Rails server and insert it inside of the main controller's element ( this.element ). For example:

<div class="container" data-controller="test">
  <button data-action="test#show">Do the Thing</button>
  <!-- partial would appear here -->
</div>

您正在寻找的是 Stimulus 的兄弟库Turbo ,用于通过 turbo-frames 处理 HTML 导航并通过 turbo-streams 部分更新页面。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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