Struggling to work with Rails 5.1's webpacker gem and VueJS, I am unable to pass data from my erb views to VueJS components...
Imagine I have a user show view
# view/users/show.html.erb
<%= javascript_pack_tag "user-card" %>
<%= content_tag :div,
id: "user-card",
data: {
username: @user.name
} do %>
<% end %>
Here is the corresponding javascript:
// app/javascript/packs/user-card.js
require("user-card")
// app/javascript/user-card/index.js
import Vue from 'vue/dist/vue.esm'
import UserCard from './components/UserCard'
document.addEventListener('DOMContentLoaded', () => {
let element = document.getElementById("user-card")
let username = element.dataset.username
console.log(username); // => "pecpec"
const app = new Vue({
el: element,
template: '<UserCard/>',
components: { UserCard },
data () {
return { username }
}
})
// app/javascript/user-card/components/UserCard.vue
<template>
<div>
<h3>Hello {{ username }}</h3>
</div>
</template>
<script>
export default {
props: ['username'],
data () {
return {
username: ""
}
}
}
</script>
I've been struggling for hours on this issue without success. I've tried passing the data as a prop:
props: ['username']
, then mounting the component using
Vue.component(UserCard, {
props: ['username']
// or
data () {
return { username: username }
}
})
... but nothing seems to be working
Update:
I included props: ['username']
in the component as suggested, however, it has not made any difference. Still no luck!