vuejs / Discussion

Vue.js discussion
167 stars 17 forks source link

How to append the the html via ajax and bind it with vue instance? #420

Closed ronakprogrammer closed 9 years ago

ronakprogrammer commented 9 years ago

Hello All,

I am trying to add the html dynamically under ul. see below code

            <div id="demo">
                <ul id="list_music">
                    <li v-model="name_0" data-id="name_0">{{ name_0 }}</li>
                    <li v-model="name_1" data-id="name_1">{{ name_1 }}</li>
                    <li v-model="name_2" data-id="name_2">{{ name_2 }}</li>
                    <li v-model="name_3" data-id="name_3">{{ name_3 }}</li>
                </ul>
            </div>

           var demo = new Vue({
            el: '#demo',
            data : {

            },
            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 = response;

                            var str = '';    
                            $.each(response, function (k,v){
                                var nameBlock = $("ul#list_music").find('[data-id="' + k + '"]');
                                if(nameBlock.length == 0){
                                    str += '<li v-model="'+k+'" data-id="'+k+'">'+v+'</li>';
                                }
                            });

                            if(str != ''){
                                var element = $("ul#list_music");
                                element.append(str);
                                var elm = $("ul#list_music li");
                                var index = elm.length-1;
                                self.$compile(elm.get(index));
                            }
                        }
                    });
                }
            }
        });

and my php code looks like this $array = [ "name_0" => "Test name 0", "name_1" => "Test name 1", "name_2" => "Test name 2", "name_3" => "Test name 3", "name_4" => "Test name 4" ];

echo json_encode($array);

So what I want to achieve this when I add any new value in $array it will insert an li tag and if I change any value from php code it should get update.

how can I achieve this using vue.js?

Thanks, Ronak Shah

theosyslack commented 8 years ago

@ronakprogrammer Did you find a solution for this?

chrise86 commented 8 years ago

Did either of you @theosyslack or @ronakprogrammer find a solution?