javascript - 当由ajax请求填充时,vue.js中的数据变量不会出现在 View 中

标签 javascript html vue.js vuejs2

我有下面的代码,“tarefas”变量没有出现在我的 v-for 中,我验证了服务器的响应,一切正常,数据即将到来。当我在输入字段中添加新数据时,它可以正常工作

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> 

最佳答案

由于您的回调是常规函数,因此您的 this 并未指向 Vue.尝试使用箭头函数。

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

参见How to access the correct this inside a callback?

关于javascript - 当由ajax请求填充时,vue.js中的数据变量不会出现在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44831943/

相关文章:

javascript - 使用 VueJS 和 Axios 从外部 API 列表呈现

javascript - NodeJS : invalid array length Allocation failed - JavaScript heap out of memory

javascript - npx react-native 链接命令在最新版本的 react native 中不起作用。我们如何在我的项目中链接自定义字体系列

javascript - vue loader 一个扩展的不同加载器

javascript - 2x if 语句 (sel.options[sel.selectedIndex].value)

html - 需要单独的 html 文件中的菜单

vuejs2 - 在突变 (Vuex) 后更改路由 (VueRouter) 的最佳实践

javascript - 无法从 html 调用静态方法

javascript - 引用错误: event is not defined on addEventListener()

javascript - if 语句在这段代码中永远不起作用