Having issues with Vue.js integration with Rails

My goal is to make an AJAX call to a Rails Controller in order to retrieve some data and then display it using Vue.js. However, for some reason, the request doesn't seem to be reaching the Controller. Can you help me figure out what I am doing wrong? Without the AJAX call, Vue.js works perfectly fine.

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

Answer №1

Instead of using ready, consider using 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;
      }
    });
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the process of choosing and displaying all articles belonging to the logged-in user with JavaScript and MongoDB!

Using the code snippet below, I am able to retrieve all articles: getAllPost: (req, res) => { Article.find({}).limit().populate('author').then(articles => { res.render('home/AllPost',{ articles ...

Encountering an Uncaught TypeError when attempting to read properties of undefined, specifically 'backdrop', while incorporating a bootstrap 5 modal within a react environment

An issue occurred when attempting to display a Bootstrap 5 modal using JavaScript. const handleClick = (e) => { e.preventDefault(); const modalElement = document.getElementById('editUserModal'); const modal = Modal.getOrCreateInsta ...

Using jQuery Flot to dynamically load data onto the x-axis from an array

I have a jQuery flot graph that loads the x-axis data as follows: xaxis: { tickColor: 'transparent', tickDecimals: 0, ticks: ticks }, When I manually set the ticks variable like this, everything works fine and the x-axis displays the 7 da ...

Creating a seamless connection between a nodejs backend and a frontend interface

I'm facing an issue with my CRUD app developed using nodeJs. The app interacts with a mysql database to perform Create, Insert, Delete, and Read operations. Here's an example of a read operation: app.get('/run',(req,res) => { con ...

Encountering a "Can't find variable" error in Java when using Ghostdriver 1.2.1 with PhantomJS 2.0 and the newest version

[ALERT - 2016-01-16T02:22:00.898Z] Session [e6651a90-bbf7-11e5-9061-cff578894101] - page.onError - msg: ReferenceError: Can't find variable: data :262 in error [WARNING - 2016-01-16T02:22:00.898Z] Session [e6651a90-bbf7-11e5-9061-cff578894101] ...

The error message "buildParams: Exceeded maximum call stack size with Uncaught RangeError" was

I'm having trouble pinpointing the mistake. Can someone please assist me? Every time I submit the form, I encounter the following error in the console: Uncaught RangeError: Maximum call stack size exceeded at buildParams I've looked at variou ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

Step-by-step guide to linking/referencing multiple scripts in an HTML file using React (no NODE.js required)

I'm currently working with React.js without Node.js, and I'm facing an issue linking multiple script files in my HTML file. Here is a snippet of my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Simple method to toggle visibility of forms using an AngularJS Button

I am hoping to create a seamless user experience by having a Login/Register button that, when clicked, reveals the corresponding form without validating anything in the JavaScript code. The goal is to have the form slide out when the button is clicked, and ...

Preventing Broken URLs in Jquery each

What is the best way to prevent taking images with broken URLs? jQuery.each(jQuery('img'), function(index, obj) { imageStack.add(jQuery(obj)); }); ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Prevent elements from shifting when you zoom in on the page

After extensive effort and research, I have successfully discovered a method to resize page elements without distortion when zooming by utilizing "vh" and "vw" units instead of "px" or "em". The current issue arises when zooming in causes the elements to ...

Expand the width of the image gradually until it reaches its initial size within a flexible DIV container

I am working with a <div> container that occupies 80% of the screen on a responsive page. Within this <div>, I am attempting to display an image that is sized at 400 x 400 pixels. My objective: As the screen width increases: The <div> ...

Steps for dynamically loading the correct pane without having to refresh the header, footer, or left navigation

Looking to create a web application using HTML, Bootstrap, and jQuery that includes a header, footer, left navigation, and right pane. The content of the right pane will be loaded from a separate HTML page based on what is clicked in the left navigation. ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

Choosing the entire contents of a webpage using jQuery

Is there a way to use jQuery to select all the content on a webpage and copy it to the clipboard for use in another WYSIWYG editor? Here's the scenario: $("#SelectAll").click(function(){ //CODE TO SELECT ALL THE CONTENTS OF THE CURRENT PAGE /* PS: $ ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Utilize the i18n tag for seamless translation

I am facing a challenge with my latest Vuejs project. I have implemented vuei18n similar to another project in my company, however, the tag is not working correctly in the new project. After turning off <code>silentTranslationWarn in i18n/index.js, ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...