3

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

I don't think compiled should be in the methods {}.
0

you can do that with vue-resource. Include vue-resource.js into your app or html file and:

    {
  // GET /someUrl
  this.$http.get('/someUrl').then(response => {

    // get body data
    this.someData = response.body;

  }, response => {
    // error callback
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.