[Vuejs]-Vue JS lists items v-repeat track-by attribute not working

0👍

Got the solution!

Here is the working code:-

var demo = new Vue({
                el: '#demo',
                data : {
                    musics : null,
                    uid : [

                    ]
                },
                created: function () {
                    //this.fetchData();
                    setInterval(this.fetchData, 5000);
                },
                methods : {
                    fetchData: function(){
                        var self = this;
                        console.log('test');
                        $.ajax({
                            type: "POST",
                            dataType : "json",
                            url : "test.php",
                            data: {},
                            success: function (response){
                                //self.$data.musics = response;
                                if(self.$data.musics != null){
                                    $.each(response, function (k,v){
                                        if(jQuery.inArray(v._uid, self.$data.uid) !== -1){
                                            var key = getKey(v._uid, self.$data.musics);
                                            self.$data.musics.$set(key,v);
                                        } else {
                                            self.$data.musics.push(v);
                                            self.$data.uid.push(v._uid);
                                        }
                                    });
                                    console.log(self.$data.uid);
                                } else {
                                    self.$set("musics", response);
                                    $.each(response, function (k,v){
                                        self.$data.uid.push(v._uid);
                                    });
                                    console.log(self.$data.uid);
                                }
                            }
                        });
                    }
                }
            });

            function getKey(uid, musics){
                var key;
                $.each(musics, function (k,v){
                    if(v._uid == uid){
                        key = k;
                        return false;
                    }
                });

                return key;
            }

The above code will append new li, or update the value of changed li.

Enjoy!
Ronak Shah

Leave a comment