Alex.Barylski
Alex.Barylski

Reputation: 2933

Vue 3 component - trying to call AJAX

I am trying to use Vue to make a bootstrap modal dynamic...

Component HTML:

 <div id="commentList">
     <comment-list
         v-for="comment in comments"
         :key="comment.id"
         :content="comment.content"
     ></comment-list>
 </div>

JS

<script>
 const app = Vue.createApp({
        data() {
            return {
                comments: []
            };
        },
        created () {
            this.fetchComments();
        },
        methods: {
            fetchComments: function () {
                $.ajax({
                    url: '/activity/head/52',
                    method: 'GET',
                    success: function (data) {
                        this.comments = data;
                    }
                });
            }
        }
    });

    app.component('comment-list', {
        props: ['content'],
        delimiters: ['{:', ':}'],
        template:
            `
                <div class="row my-4">
                    <div class="col-1"><img src="/photo-alex.jpg" class="rounded-circle" style="width:38px; height: 38px"></div>
                    <div class="col-11 p-3 text-muted rounded bg-white border">
                        {:content:}
                    </div>
                </div>
            `
    });

    app.mount('#commentList');
</script>

The AJAX request isn't being executed, so that's the first issue I am encountering, thoughts?

AJAX response:

[
  {
    id: 76,
    ago: "in 4 hours",
    user: "Alex",
    content: "THIS IS A COMMENT"
  }
]

Upvotes: 0

Views: 6658

Answers (1)

tao
tao

Reputation: 90003

You're using a normal function for $ajax.success. Inside it, this is that function's context, not the Vue instance. Change it to an arrow function so it has access to the outer scope, which will allow it to assign the response to the Vue instance's comments. Basically:

fetchComments: function() {
  $.ajax({
    url: '/activity/head/52',
    method: 'GET',
    success: function(data) {
      this.comments = data;
    }
  });
}

Should become:

fetchComments() {
  $.ajax({
    url: '/activity/head/52',
    method: 'GET',
    success: data => {
      this.comments = data;
    }
  });
}

Note: changing from fetchComments: function(){ ... } to fetchComments() { ... } is irrelevant. They're the same thing, it's just I prefer the shorter syntax.

What matters is changing success from function(data) { ... } to data => { ... }.

Upvotes: 2

Related Questions