【问题标题】:Rails + Vue.js - Using Ajax to update Vue componentRails + Vue.js - 使用 Ajax 更新 Vue 组件
【发布时间】:2019-05-07 17:12:36
【问题描述】:

我有一个使用 webpacker 的 Rails 5 应用程序,它显示用户列表。这样做的逻辑是在其中包含 Vue 组件代码的部分中,例如

<profile_modal>

  <template slot="trigger">

    <figure class="profile-card__figure | image -is1x1">
      <img src="<%= person.avatar.url %>" alt="">
    </figure>
...

一切正常,.erb 在处理页面时将其正确更改为 HTML。到目前为止一切顺利。

现在我添加了一个按钮,上面写着“显示更多用户”,该按钮通过 ajax 调用来吸引更多用户。我制作了一个 js.erb,其中包含:

$("#users").html("<%= escape_javascript(render partial: 'layouts/components/profile-card--modal', collection: @users.last(12), as: :person, locals: { content: @users_presenter.profile_modal }) %>"); 

此代码已执行,但不是将“profile_modal”转换为正确的 html,rails 只是将其插入到页面中,这使得一切都出错了。

有没有办法可以将 vue 代码转译成在正常、非 ajaxy 处理期间会变成的 html?

【问题讨论】:

  • 为了分解您的步骤,您创建了一个按钮 show more users,该按钮对 yourfile.js.erb 进行了 ajax 调用。该文件包括以下 javascript $("#users").html(....) 附加到 #users 部分 profile-card--modal 的 html 和 @users.last(12) 的数据。这最后一步我不清楚。 This code is executed, but instead of converting the "profile_modal" to the right html, rails is just inserting it right in the page, which makes everything wrong. 通过屏幕截图或实际源代码查看您描述的实际效果会很有用。谢谢
  • @FabrizioBertoglio 抱歉,不清楚。部分已成功添加到 DOM 并按预期将其添加到页面上。但是,不是将包含诸如“”之类的 Vue 内容的部分代码更改为正确的 HTML,因为它在 html.erb 中的相同代码中,而是按原样吐出代码,因此当您检查在浏览器中调用 ajax 后,您会在代码中看到标记“”,这显然是不正确的。希望这个解释是有道理的。谢谢!
  • &lt;profile_modal&gt; 是某种组件,javascript 应该用 html 替换它,但是当您运行 $("#users").html() 时,它会直接附加到页面上。只有asynchronous javascript request 没有运行完整页面重新加载,您才有这个问题?这意味着我们可以将问题隔离到Webpacker with Vue 无法正常工作?您正在使用 javascript 格式的 rails 控制器回复并使用 .erb.js 视图。
  • 你是使用vue的服务端渲染还是客户端渲染?如果是客户端渲染,Vue可能会在页面上有一个监听器来检测变化并执行javascript来渲染vue组件。我相信服务器渲染不需要客户端运行javascript来渲染html,你不会遇到这个问题。

标签: ruby-on-rails ajax vue.js ruby-on-rails-5


【解决方案1】:

你不应该为整个组件调用渲染,你应该创建一个全局组件来接收用户数组作为变量,如下所示:

window.users = [
  { id: 'this-is-an-id', name: 'Evan', age: 34 },
  { id: 'unique-id', name: 'Sarah', age: 98 },
  { id: 'another-unique-id', name: 'James', age: 45 },
];

<ul>
  <li v-for="person in users" :key="person.id">
    {{ person.name }} - {{ person.id }}
  </li>
</ul>

然后,当您更改 users 变量时,您的 Vue 组件也会发生变化。因此,不要覆盖组件的整个 HTML,而是将 .js.erb 附加到 users 变量:

response_users = <%=j @users.last(12).as_json %>;
Object.assign(users, response_users);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 2020-04-14
    • 2018-04-12
    • 2018-05-05
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多