Using Vue components in Rails specific javascripts with Webpacker in Rails 5.1+
Two weeks ago I have written an article about Using Vue in controller specific javascripts with Webpacker in Rails 5.1+. I’m using it every day, but now the need of Vue components came up.
I was curious if it is possible without any bigger changes. And it is!
Creating new component is the same as usual, just do it inside the /app/javascript/packs
folder:
// /app/javascript/packs/components/test.vue<template>
<h1>{{name}}</h1>
</template>
<script>
export default {
props: ['name']
}
</script>
Using of component is super simple with one tweak:
import Vue from 'vue'
import Test from './components/test'var element = document.getElementById('test')
if (element != null) {
var test = new Vue({
el: element,
components: {
myTest: Test
}
})
}
Just notice the wierd path when loading component import Test from './components/test'
! Webpack is considering /app/javascript/packs
as the root folder not /app
! Keeping this in mind when loading components.
And the view?
Using component in html.erb file is easy as well:
# /app/views/users/index.html.erb<ul id="test">
<li v-for="user in users">
<my-user :name="user.name"></my-user>
</li>
</ul>
Do you like it? Clap!