0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails内にVueを導入した時のviewはどう書く?

Last updated at Posted at 2020-12-20

まずはvueをrailsのvueに表示させてみる。

controllerとviewを作る

rails g controller Pages home

下のコードで、app/javasript/packs配下にあるファイルを読み込むことができる。CSSも

<%= javascript_pack_tag 'hello_vue' %>  
<%= stylesheet_pack_tag 'hello_vue' %>   

app/view/application.html.erb

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    +<%= javascript_pack_tag 'hello_vue' %> 
    +<%= stylesheet_pack_tag 'hello_vue' %> 
  </head>

  <body>
    <%= yield %>
  </body>
</html>

ブラウザを確認して見ると、、、
Image from Gyazo

次は、railsのviewからvueを操作するプロセス

app/javascript/packs/hello_vue.js
import Vue from 'vue'
import App from '../app.vue'

document.addEventListener('DOMContentLoaded', () => {
  const app = new Vue({
    render: h => h(App)
  }).$mount()
  document.body.appendChild(app.$el)

  console.log(app)
})


// The above code uses Vue without the compiler, which means you cannot
// use Vue to target elements in your existing html templates. You would
// need to always use single file components.
// To be able to target elements in your existing html/erb templates,
// comment out the above code and uncomment the below
// Add <%= javascript_pack_tag 'hello_vue' %> to your layout
// Then add this markup to your html template:
//
// <div id='hello'>
//   {{message}}
//   <app></app>
// </div>


// import Vue from 'vue/dist/vue.esm'
// import App from '../app.vue'

// document.addEventListener('DOMContentLoaded', () => {
//   const app = new Vue({
//     el: '#hello',
//     data: {
//       message: "Can you say hello?"
//     },
//     components: { App }
//   })
// })

中央のコメントアウトされている文章を読んで見ると、上をコメントアウトして、下のコメントアウトを外してくれ。そして、下のコードをerbにペースとしてくれと書かれている。

app/javascript/packs/hello_vue.js
import Vue from 'vue/dist/vue.esm'
import App from '../app.vue'
import Home from './pages/Home.vue'


document.addEventListener('DOMContentLoaded', () => {
  const app = new Vue({
    el: '#hello',
    data: {
      message: "Can you say hello?"
    },
    components: { App }
  })
})

ブラウザ側

home.html.erb
<div id='hello'>
  {{message}}
  <%# ↓app.vueの読み込み %>
  <app></app>
  <h1>Pages#home</h1>
</div>

Hello.vueとcan you say hello?が表示されて入れば完了です。

終わりです。

参考:
https://qiita.com/cohki0305/items/582c0f5ed0750e60c951

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?