Pedro Henrique Silva
Pedro Henrique Silva

Reputation: 168

Data variable in vue.js is not appears in the view when populated by ajax request

I have the code below, the 'tarefas' variable is not appear in my v-for, and I verify the response from the server and its ok, the data are coming. When I add new data in the input field, it works correctly

JS:

var app = new Vue({

el: '#app',

data: {
    titulo: 'Lista de Tarefas',
    tarefas: [],
    tarefa: ''
},

methods: {
    addTarefa: function () {
        console.log(this.tarefa);
        if (this.tarefa !== '') {
            this.tarefas.push({identificador: 0, descricao: this.tarefa, feito: 0});
            this.postTasks();
            //this.tarefa = '';
        }
    },

    removerTarefa: function (tarefa) {
        this.tarefas.splice(this.tarefas.indexOf(tarefa), 1)
    },

    syncTasks: function () {
        jQuery.get('http://localhost:51622/api/tarefa', function (data, status) {
            this.tarefas = data;
            console.log(data);
            console.log(this.tarefas);
        });
    },

    postTasks: function () {
        jQuery.post('http://localhost:51622/api/tarefa', {identificador: 0, descricao: this.tarefa, feito: 0});
    },
},

created: function () {
    console.log("passei no mounted");
    this.syncTasks();
},});

HTML:

<p class="text-primary center">{{ titulo }}</p>
        <div class="col-xs-3">
            <input type="text" placeholder="digite a tarefa" v-model="tarefa" class="form-control" />
        </div>
        <button v-on:click="addTarefa" class="btn btn-default">add tarefa</button>
        <br />

        <br />
        <div class="col-xs-3">
            <ul class="list-group">
                <li v-for="tarefa in tarefas" class="list-group-item">{{ tarefa }} <button class="btn" v-on:click="removerTarefa(tarefa)">X</button></li>
            </ul>
        </div>

    </div>
</div>
<script src="app.js"></script> 

Upvotes: 0

Views: 45

Answers (1)

Bert
Bert

Reputation: 82499

Since your callback is a regular function, your this is not pointing to the Vue. Try an arrow function.

jQuery.get('http://localhost:51622/api/tarefa', (data, status) => {
    this.tarefas = data;
    console.log(data);
    console.log(this.tarefas)
});

See How to access the correct this inside a callback?

Upvotes: 1

Related Questions