Rails Vuejs Webpacker: passing instance variable data

I am trying to learn how to create a Rails 5.1 application using Vuejs, created using the Webpacker gem.

$ rails new myvueapp --webpack=vue

How do I pass instance variable data back on Thursday between Vue components to get my data to / from the database?

Say, for example, that I have a User model with the Username and Email fields. Is there a simple example of how to pass an instance variable, @user, data from a controller to a component?

I believe that there are two ways to do this:

(1) There is in the controller render :json => @user, and then use something like the Fetch or Axios API to retrieve the data in the .vue component.

-or-

(2) Use something like an example <%= javascript_pack_tag 'hello_vue' %>along with <%= content_tag ... %>in a view.

When I do this example <%= javascript_pack_tag 'hello_vue' %>, I see "Hello Vue!". from the data in the component "message" variable, but I find it difficult to find an example of the data of instance variables, for example: @user data that is sent and exited from Rails.

Any examples of how to transmit @user data would be much appreciated.

Thank.

+5
source share
2 answers

I am not 100% sure what you are trying to accomplish, but I can imagine two ways to do this.

  • Use v-modelin shape. No matter what value is retrieved or updated, it will be used immediately in your Vue instance. (eg,<%= f.input :username, input_html: { 'v-model': 'username' } %>

  • . , @user.

, , - ( 100% , ):

<% simple_form_for @user do |f| %>
  <%= f.input :username, input_html: { id: 'user_username', data: { username: @user.username } } %>
  <%= f.input :email, input_html: { id: 'user_email', data: { email: @user.email } } %>
<% end %>

JavaScript . , , v-model, . , URI, AJAX, ..

+1

, , : window :

// app/javascript/packs/some_app.js

window.someAppPack = function (var1, var2) {
  // ...
  new Vue({
    // ...
    data () {
      return {
        var1,
        var2,
      }
    }
    // ...
  })
}

Rails:

<%= javascript_pack_tag 'somePack' %>

<script>
  someAppPack(#{raw @var1.to_json}, #{raw @var2.to_json})
</script>

, , :

  • Vue , - , JSON. .
  • Vue , , -, "" Vue Rails?
0

Source: https://habr.com/ru/post/1682454/


All Articles