【问题标题】:Axios can't set dataaxios无法设置数据
【发布时间】:2017-04-21 03:36:02
【问题描述】:

这是我的数据:

data: function(){
    return {
        contas: [{id: 3,
            nome: "Conta de telefone",
            pago: false,
            valor: 55.99,
            vencimento: "22/08/2016"}] //debug test value
    };
},

这是我的获取请求:

beforeMount() {
    axios.get('http://127.0.0.1/api/bills')
        .then(function (response) {
            console.log("before: " + this.contas);
            this.contas = response.data;
            console.log("after: " + this.contas);
        });
},

问题是我无法从axios.get() 中访问this.contas。我试过Vue.set(this, 'contas', response.data);window.listaPagarComponent.contas = response.data; 都没有成功。

我的控制台显示:

before: undefined
after: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

但 Vue Devtools 只显示:

contas: Array[1]
  0: Object
    id: 3
    nome: "Conta de telefone"
    pago: false
    valor: 55.99
    vencimento: "22/08/2016"

这是我的full code

【问题讨论】:

  • 尝试使用created()钩子而不是beforeMount()。如果你已经在contas数组中定义了一些数据,那么我认为你应该做array.push。
  • 好的,你能在数据模型中创建新数组,并设置响应数据吗?然后结帐,项目是否存储在数组中。不幸的是我不使用 Axios,我宁愿使用 Vue 资源。
  • @Belmin 没有任何变化......而且它只是一个调试测试值。我不想要这个值。问题是我不能使用this.contas 来引用组件的数据contas。没有功能起作用。我认为axios是一个“对象”,所以当我使用this时,它指的是axios。
  • 是的,已经尝试过使用字符串。字符串var test = ''。然后什么都没有改变。我认为this 以某种方式指代 axios。 Vue 资源不适用于 Vue.js 2
  • 不确定,对不起,我说过我从未使用过 Axios。Vue 资源与 Vue 2 完美配合。我在许多项目中都使用过它。查看 jsbin.com/jeqekexiqa/edit?html,js,console,output

标签: vue.js axios


【解决方案1】:

datacreated这样的选项函数中,vue为我们绑定了this到view-model实例,所以我们可以使用this.contas,但是在thenthis里面的函数里面是不受约束。

所以需要像这样保存view-model(created表示组件的数据结构已经组装好了,这里就够了,mounted会更耽误操作):

created() {
    var self = this;
    axios.get('http://127.0.0.1/api/bills')
        .then(function (response) {
                self.contas = response.data;
                });
}

或者如果你只打算支持现代浏览器(或使用像 babel 这样的编译器),你可以使用 ES6 标准中的箭头函数,例如:

created() {
    axios.get('http://127.0.0.1/api/bills')
        .then((response) => {
                this.contas = response.data;
                });
}

this里面的箭头函数是根据词法上下文绑定的,也就是说上面sn-p中的thiscreated中的一样,就是我们想要的。

【讨论】:

  • 万岁!这也解决了我的问题...谢谢。无论我学习和理解多少次“这个”,它总是会给我带来问题。
  • 太感谢了,因为需要'this'语法的实例
【解决方案2】:

为了能够在 axios.get() 中访问 this.contas,您是否需要绑定“this”以保持变量使用范围:

mounted() {
    axios.get('http://127.0.0.1/api/bills')
     .then(function (response) {
        console.log("before: " + this.contas);
        this.contas = response.data;
        console.log("after: " + this.contas);
     }.bind(this));
}

【讨论】:

  • 这个也是真的
猜你喜欢
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2018-02-16
  • 2018-05-24
  • 2021-07-18
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
相关资源
最近更新 更多