LoginSignup
1
0

More than 3 years have passed since last update.

Railsのerbのeach内でVueのComponentを使いたい

Last updated at Posted at 2019-07-12

やりたいこと

記事の一覧を表示させて、各記事ごとにいいねボタンのVueComponentを設置したい

最初考えた方法

top.html.erb
<% @articles.each do |article| %>
  <h1><%= article.title %></h1>
  <p><%= article.description[1, 80] %></p>

  <!-- 記事の個数分のVueインスタンスを作成しなくてはいけないじゃまいか... -->
  <like-button-component></like-button-component>
<% end %>

こんな感じでかきました

top.html.erb
<!-- eachの外側をdivでくくって全体をVueインスタンスにした -->
<div id="articles-wrapper"> <!-- ←追加 -->
  <% @articles.each do |article| %>
    <h1><%= article.title %></h1>
    <p><%= article.description[1, 80] %></p>

    <!-- いいねボタンのcomponent -->
    <like-button-component></like-button-component>
  <% end %>
</div> <!-- ←追加 -->

<script src="js/main.js"></script>
main.js
import SocialButtons from './components/SocialButtons.vue';
import Vue from 'vue';

new Vue({
  el: '#articles-wrapper',
  components: { SocialButtons },
});

さいごに

今回SEOの観点から記事の内容などのメインコンテンツはサーバーからhtmlの状態で返したいとの要望がありこのような方法をとりました。こんな感じでVueのテンプレート部分を記述されたHTMLそのまま使うこともできるのが勉強になりました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0