Skip to content
Advertisement

Vue.js with Rails not working

I am trying to send an AJAX call to Rails Controller to fetch some data and use Vue.js to output it. But it doesn’t seem to be sending any kind of request to the Controller. What am I doing wrong here? Vue.js does work without AJAX call

app/assets/javascript/calculator.js

var calculator = new Vue({
  el: '.container',
  data: {
    numbers: []
  },
  ready: function() {
    var that;
    that = this;
    $.ajax({
      url: '/calculator.json',
      success: function(response) {
        that.numbers = response;
      }
    });
  }
});

app/controllers/calculator_controller.rb

class CalculatorController < ApplicationController
  def index
    @numbers = [1,2,3,4,5]
    respond_to do |format|
      format.html
      format.json { render json: @numbers }
    end
  end
end

app/views/calculator/index.html.haml

.container
  .row
    .col-lg-12
      %ul
        %li{ "v-for": "number in numbers" }
          {{ number }}

Advertisement

Answer

Instead of ready try mounted:

var calculator = new Vue({
  el: '.container',
  data: {
    numbers: []
  },
  mounted: function() {
    var that;
    that = this;
    $.ajax({
      url: '/calculator.json',
      success: function(response) {
        that.numbers = response;
      }
    });
  }
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement