[Vuejs]-How to access Rails instance variable from Vue.js component?

-1👍

You can pass Rails variables to Javascript, but you need to embed them in the HTML page first, and your JS code reads them from the HTML.

Insert your variables into the HTML like this.

<%= content_tag :div, class: "variables", data: { 
  first_variable: @variable_1,
  second_variable: @variable_2 
} do %>
<% end %>

This will output a div in the generated webpage like this.

<div class="variables" data-first-variable="[VALUE]" data-second-variable="[VALUE]">

You then read them into your JS like this.

$('.variables').data('firstVariable')

(This is JQuery notation, as you’ll see, but I’m sure you can do something similar in Vue.)

Leave a comment