Vue.js 2 is known to display an empty array on the

Incorporating vue.js into my laravel project has presented a challenge. Despite having data in the variable names, vue.js is rendering an empty array.

I am using laravel 5.4 and vue.js2, with vue-resource for the jsonp get method.

When attempting to display the variable containing data {{names}} in the template, it only shows an empty array without any error logs appearing.

template.vue

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-body">
                    {{names}}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

Js

<script>
    export default {
        data: function(){
            return {
              names: []
            };

        },
        methods:  {
         getData: function(){
             var self = this;
              // GET request
           this.$http.jsonp(url, {jsonpCallback: "JSON_CALLBACK"})
           .then(response=>{
               return response.body;              
           })
           .then(data =>{
               self.names = data
                console.log(JSON.stringify(self.names))// logs the data 
           })
        }
      },
       mounted() {
            this.getData()

            console.log('Component mounted.')
        }
    }
</script>

blade.php

<search id='search'>
</search>

The JSON response is as follows:

[
   {
      "uri":"http://en.wikipedia.org/wiki/Samsung",
      "id":"24366",
      "type":"org",
      "score":527013,
      "label":{
         "eng":"Samsung"
      }
   },
   {
      "uri":"http://en.wikipedia.org/wiki/Samsung_Electronics",
      "id":"30860",
      "type":"org",
      "score":135216,
      "label":{
         "eng":"Samsung Electronics"
      }
   }
]

vue dev tools reveal the variable https://i.sstatic.net/bK8Rf.png

Answer №1

I took the liberty of compiling your code into a functioning snippet, and it seems to be working correctly after making some adjustments. I had to modify the data request part.

It appears that there might be an issue with the self variable not behaving as expected during the assignment process. The cause of this behavior is currently unknown to me.

new Vue({
  el: '#search',
  components: {
    search: {
      data: function() {
        return {
          names: []
        };

      },
      methods: {
        getData: function() {
          const self = this;

          setTimeout(function () {
            self.names = [{
                "uri": "http://en.wikipedia.org/wiki/Apple",
                "id": "112233",
                "type": "org",
                "score": 987654,
                "label": {
                  "eng": "Apple"
                }
              },
              {
                "uri": "http://en.wikipedia.org/wiki/Microsoft",
                "id": "445566",
                "type": "org",
                "score": 543210,
                "label": {
                  "eng": "Microsoft"
                }
              }
            ];
          }, 0);

        }
      },
      mounted() {
        this.getData()

        console.log('Component has been mounted. The current state of names array is:', this.names);
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<search id='search' inline-template>
  <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
          <div class="panel-body">
            {{names}}
          </div>
        </div>
      </div>
    </div>
  </div>
</search>

Answer №2

After some troubleshooting, I managed to fix the problem. Interestingly enough, it turned out that the issue was originating from how I initialized my component:

Vue.component('search', require('./components/Searchnames.vue'));

const search = new Vue({
    el: '#search'
});

It seems that in a separate file, I referenced data and methods using export default, which caused the problem. By removing the following code snippet:

const search = new Vue({
    el: '#search'
});

I was able to resolve the issue. It's still unclear why this particular setup was causing trouble.

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

How can you create a personalized sorting order using odata?

Within my AngularApp, I retrieve data from a WebAPI using OData queries. All the retrieved results contain both a date and an integer status code. The status codes range from 1 to 4. I am aiming to organize my results in such a way that all items with a ...

Pusher: Received no callbacks for testing the pusher functionality on my event

I am attempting to implement a feature where each object I create is broadcasted without the need to refresh the page. Below is the JavaScript code for initializing Pusher and binding the event for UserHasRegistered: <script src="https://js.pusher. ...

Guide to developing a personalized useReducer with integrated decision-making and event activation

I am interested in creating a custom hook called useTextProcessor(initialText, props). This hook is designed for managing and manipulating text (string) within a React state. It utilizes useReducer to maintain a cumulative state. Here is the implementation ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

The first three AJAX requests are successful, but the fourth one fails to reach the PHP script

I am currently working on cascaded selects (a total of 4) that retrieve data from a database. To populate them, I use SQL queries based on the selection made in the previous select element. To establish communication between the select element and the subs ...

Error encountered when attempting to retrieve data from a JSON object

I'm in the process of extracting some information from a JSON object, but I've encountered a confusing issue. The JSON object structure is as follows: { "status": "success", "data": { "image": null, "video": null, "author": null, "publisher": "M ...

Verify the duration of the video upon uploading - Angular

I am having trouble checking if the video I uploaded is longer than 30 seconds, and I am struggling to find a suitable example. Below is the code snippet that includes size checking among other things: readVideoUrl(event: any) { this.videoFile = []; ...

Looping through elements using .each in jQuery and accessing their values in the following iteration

Here is the code snippet I've been working on: var index=0; var load=0; $("td.load_ads").each(function(){ var loading=$(this); $.post('/self_coded_helpers/jpost_get_ads.php',{index:index,type:'fetch_id' ...

What are the steps to limit entry to a page in Rails unless the user has come through a designated link on another page?

I'm currently developing an online computer-based test using Rails. Each question is accessed through a unique page URL in the format /questions/<id>. On each question page, there is a 'next' button that directs users to the follow ...

Getting the most out of geometry vertices with Threejs: mastering partial transforms

In my current project, I am working with a mesh that consists of approximately 5k vertices. These vertices have been merged from multiple geometries into a flat array. Initially, I was able to modify individual vertices successfully by setting the flag `ve ...

Select a particular checkbox within an HTML table

One of the challenges I'm facing involves working with a HTML table that has a column filled with checkboxes. I'm looking for guidance on how to utilize Javascript to mark a checkbox at a particular row index as checked, without relying on jquery ...

Guide to altering the color of text entries in the search bar using a clickable button

Is there a way to display multiple values in the search field using a single button, and also have them appear in a specific color such as green? http://jsfiddle.net/7bpaL5hy/ <form id="form1" name="form1" method="post"> <p> < ...

I am interested in having a bilingual link on the main page that directs users to the corresponding page in Spanish or English, rather than back to the homepage

I am currently working on a Visual Studio C# .NET project that has both English and Spanish versions. Each version has its own master template with a link to switch between languages. However, clicking on the language link takes me to the homepage of the c ...

I am encountering a JSON parsing error while trying to implement jQuery autocomplete, despite using a local array

I'm attempting to implement the jQuery autocomplete feature on a WordPress website. My ultimate goal is to link the input field to an ajax request that will retrieve data from a database. However, I've encountered an unusual error when trying to ...

A guide on updating the SQL order value through a select option using PHP and jQuery

To modify the arrangement of SQL data according to the chosen select option, I am looking to adjust the ORDER value. Within my action.php file, I retrieve values from the database and aim to incorporate a sorting select option that allows for changing the ...

Sending dynamic internationalization resources from Node.js to Jade templates

Looking for a way to show a custom error page to the user in case of an error, but it needs to be internationalized (i18n-ed). Solution: My idea is to validate in node -> if not accepted -> res.render('error', {message: errorMessageNameToo ...

Using jQuery to determine the value and dynamically stay on the current page

Is there a way to ensure that the page stays the same if the login (data.login != 1) is incorrect? I attempted using preventDefault, but it doesn't seem to be effective. Can someone offer assistance? $(document).on('submit', '#login&ap ...

Whenever I try to utilize the "ng-list" in JavaScript, I encounter issues accessing the variable model

HTML <input type="text" ng-list ng-model="OtherHobby" />{{OtherHobby}} <br /> {{AllHobbys}} Javascript $scope.OtherHobby = []; $scope.AllHobbys = $scope.OtherHobby; I ran a test on this piece of code. The variable "OtherHobby" w ...

Step-by-step guide on filtering an array of objects using Vuejs and TypeScript

For this particular project, I am utilizing Vuejs Typescript with a data structure that looks like this: ["order": { "id":1, "created_at":"2019-12-06T10:22:17Z", "status":"open", ...

Adjusting the Global Position of a Child Element in Three.js

Is it possible to manipulate the global position of a child object in Three.js? My main objective is to: 1) Unlink the child from its parent (without changing its location) 2) Move the parent to a different position 3) Reconnect the child (without al ...