【问题标题】:Vue2 data not being updated in template after retrieving from url从 url 检索后,模板中未更新 Vue2 数据
【发布时间】:2018-05-28 01:33:23
【问题描述】:

我正在使用 Vue.js 版本 2,试图更新视图中使用的变量。

请耐心等待,我有以下代码:

new Vue({
    el: '#products',

    data: {
       showProductModal: false,
       product: {}

    },

    methods: {

      retrieveProduct(id) {
        axios.get('/product/'+id).then(function (response) {
            this.product = response.data;
            console.log(this.product);
        });
      }
  }

请注意:

  • product变量被初始化为空对象{};
  • 在用户单击按钮后调用“retrieveProduto()”方法。然后它会进行 API 调用,并在 promise 解决后更新 product 变量。
  • 我使用axios发起http请求,它返回一个response对象,其中response.data是返回对象的内容。

console.log(this.product) 结果

{id: 1, name: "柠檬蛋糕", description: "传统柠檬蛋糕", pic_url: "", category_id: 1, ...}

这正是预期的输出。但是,在视图中调用 {{ product }} 时,模板不会以任何方式更新,并且会永远卡在 {} 中。

我还测试了双向数据绑定是否有效,答案是肯定的。实际上,除此之外,一切都运行良好。难道我做错了什么?我是否应该期望在从 Promise 中检索对象后模板不会更新?

感谢任何帮助。提前谢谢你。

编辑:

  • 我在其中调用变量的模板部分只是一个用于测试目的的 {{product}}。
  • 我调用 self 的原因是我在第一次尝试时使用了 this.product。我已经看到了这个solution elsewhere 并对其进行了更改,以便我可以试一试。由于它不起作用,我将其改回 this
  • 打印 console.log(this) 会返回完整的 Vue 对象,并且它的 product 属性设置正确,但仍未反映在模板中。

【问题讨论】:

  • 在这段代码中你在哪里设置data.product?我没有看到它并给我们渲染的模板部分!
  • 你实际上从来没有声明过self
  • @WilomGfx 我已经编辑了帖子以添加一些信息。请看一看。

标签: javascript vue.js vuejs2 frontend


【解决方案1】:

您可能会遇到self 的问题,无论是由于缺少声明还是范围界定问题。请尝试以下方法:

retrieveProduct(id) {
    var this_vue_instance = this;
    axios.get('/product/'+id).then(function (response) {
        this_vue_instance.product = response.data;
        console.log(this_vue_instance.product);
    });
}

【讨论】:

  • 没用。我之前曾用 this 尝试过。请看一下修改。
  • @Cortifero 你确定要使用var this_vue_instance 行吗?如果您在 axios.get() 范围内,this 可能不会引用 Vue 实例。
  • 是的,我已将代码更改为您所建议的。完全有道理,但它不起作用。 console.log(this_vue_instance) 还显示了产品属性。但是没有反映模板中的变化
【解决方案2】:

我认为这应该是范围界定的一些问题。 试试这个:

  retrieveProduct(id) {
    axios.get('/product/' + id).then(response => {
      this.product = response.data;
    });
  }

然后使用vue-devtools检查数据是否正确更改。

【讨论】:

  • 成功了!!显然它与旧的 javascript 表示法有关。使用 .then(response => { 成功了。非常感谢
  • 很高兴它有帮助!哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-24
相关资源
最近更新 更多