1

The <project-comp></project-comp> component doesn't display when the page is loaded.I've set projects property using the created hook.But it doesn't work.

Here is my code:

Vue.component('project-comp',{
        template: `
        <div class='box'>            
            <div v-for='one in this.$parent.projects'>
               <h2> @{{one.place}}</h2>
               <h2> @{{one.time}}</h2>
            </div>
        </div>
        `,
});

var app = new Vue({
        el: '#root',

        props:['projects'],

        created: function () {
            $.post(
                'url',
                {'city':'beijing'},
                function(data){
                    this.projects = data;
                },
                'json'
            );
        },


});
yongyu
  • 97
  • 1
  • 8
  • In your given snippet, you ONLY register/create a `` for use, but where did you `mount` it in your template markup? – Allen Mar 04 '17 at 17:05

1 Answers1

3

It seems the scope of this is not correct, you should have it:

var app = new Vue({
        el: '#root',    
        props:['projects'],
        created: function () {
            var self = this
            $.post(
                'url',
                {'city':'beijing'},
                function(data){
                    self.projects = data;
                },
                'json'
            );
        },
});

With ES-6 it can be just:

var app = new Vue({
        el: '#root',    
        props:['projects'],
        created: function () {
            $.post(
                'url',
                {'city':'beijing'},
                (data) => {
                    this.projects = data;
                },
                'json'
            );
        },
});

check this for explanation.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • 2
    I created a documentation topic for this. It seems to pop up a lot. http://stackoverflow.com/documentation/vue.js/9350/using-this-in-vue#t=201703042039563445243 – Bert Mar 04 '17 at 20:42