I am trying to learn how to build an app with Rails 5.1 with Vuejs, as generated via the Webpacker gem.
$ rails new myvueapp --webpack=vue
How do I pass instance variable data back an forth between the Vue components, to get my data in/out of the database?
Let's say for example that I have a User model with Username and Email fields. Is there a simple example of how to pass instance variable, @user, data from the controller to a component?
I believe there are two ways to do this:
(1) In the controller, has the render :json => @user
and then use something like the fetch API or Axios to retrieve the data in the .vue component.
-or-
(2) Use the something like the example <%= javascript_pack_tag 'hello_vue' %>
together with a <%= content_tag ... %>
in a view.
When I do this <%= javascript_pack_tag 'hello_vue' %>
example, I can see the "Hello Vue!" from the data in the component "message" variable, but am having trouble finding an example of instance variable data, eg: @user data, being passed in and out of Rails.
Any examples of how to pass @user data would be much appreciated.
Thank you.
I did something that works but I don't really like: create a method in the window
scope like:
// app/javascript/packs/some_app.js
window.someAppPack = function (var1, var2) {
// ...
new Vue({
// ...
data () {
return {
var1,
var2,
}
}
// ...
})
}
And in the Rails template:
<%= javascript_pack_tag 'somePack' %>
<script>
someAppPack(#{raw @var1.to_json}, #{raw @var2.to_json})
</script>
This seems dirty to me, and I'm wondering the benefits :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With