简体   繁体   中英

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 }}

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;
      }
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM