[Vuejs]-Set value to Vue model from rails rendering process

0👍

I just go with a kind of tricky solution; I set my rails model variable to a Vue model variable wich get “stuck” but on the created method (using a setTimeout to delay the action ¯\_(ツ)_/¯) I reasign this value to a second and totaly free Vue model variable:

_a_single_layout.html.erb

<div id="app">
  <span class="hide-me">{{real_value = <%= @model.progress %>}}</span><!-- this variable gets the value from the rails model but also gets "stuck" -->
  <h1>{{progress}}%</h1>
  <input type="range" min="0" max="100" v-model="progress"><!-- this variable will get its real value when the "created" method starts -->
</div>

application.js

let app = new Vue({
  el: "#app",
  data: {
    progress: 0,
    real_value: 0
  },
  created: function(){
    setTimeout(() => this.progress = this.real_value, 1000)
  }
})

By the way, I am still looking for a “correct” solution.

0👍

The solution is to create a Vue component.
Then you can pass your ‘rails’ data to Vue through this component with props. You just need to convert it to JSON first:

_a_single_layout.html.erb

<div id="app">
  <load-progress :progress="<%= @model.progress.to_json %>"></load-progress>
</div>

application.js

const LoadProgress = Vue.component('load-progress', {
  template: `
    <div>
      <p>{{ progress }}%</p>
      <input type="range" min="0" max="100" :value="progress">
    </div>`,
  props: ['progress']
})

const app = new Vue({
  el: '#app',
  components: { LoadProgress }
})

Leave a comment