Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS - Putting Json on data

I want to put my JSON data into Vue data, and a display, why can't I get to work?

compiled: function(){
    var self = this;
    console.log('teste');

    $.ajax({
        url: 'js/fake-ws.json',
        complete: function (data) {
            self.$data.musics = data;
            console.log(self.$data.musics);
        }
    })
}

<div id="playlist" class="panel panel-default">
    <div class="panel-body">
        <ul>
            <li v-repeat="musics.item" >
                <a href="">{{nome}}</a>
            </li>
        <ul>
    <div>
</div>  

I can't get the code to work.. why?

like image 621
Guilherme Cruz Avatar asked Dec 29 '25 08:12

Guilherme Cruz


2 Answers

I think the problem is that musics is not initially part of your Vue data, so when you set its value using self.$data.musics = data, Vue doesn't know it needs to watch it. Instead you need to use the $add method like this: self.$set("musics", data);

From the VueJs Guide:

In ECMAScript 5 there is no way to detect when a new property is added to an Object, or when a property is deleted from an Object. To deal with that, observed objects will be augmented with two methods: $add(key, value) and $delete(key). These methods can be used to add / delete properties from observed objects while triggering the desired View updates.

like image 105
Migwell Avatar answered Dec 31 '25 23:12

Migwell


this refers to the whole Vue object, so musics object is already accessible via this.musics. More info here in the VueJS API reference and here in the VueJS guide, and more on this here.

With that in mind the code should look something like this:

var playlist = new Vue({

 el: '#playlist',

 data:{
   musics: '',
 }

 methods: {
    compiled: function(){
      var self = this;
      console.log('test');

      $.ajax({
        url: 'js/fake-ws.json',
        complete: function (data) {
            self.musics = data
            console.log(self.musics);
        }
      })
    }
 }

And the view would be something like this:

<div id="playlist" class="panel panel-default">
          <div class="panel-body">
                <ul>
                     <li v-repeat="musics">
                        <a href="">{{nome}}</a>
                    </li>
                <ul>
          </div>
    </div>  

Also look at the code of this example.

like image 43
zcuric Avatar answered Jan 01 '26 00:01

zcuric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!