javascript - 从 url 检索后,Vue2 数据未在模板中更新

标签 javascript vue.js vuejs2 frontend

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

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

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: "Lemon cake", description: "Traditional lemon cake", pic_url: "", category_id: 1, …}

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

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

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

编辑:

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

最佳答案

您可能会遇到 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);
    });
}

关于javascript - 从 url 检索后,Vue2 数据未在模板中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805254/

相关文章:

javascript - angularJS:用于模式的多个匹配的ng-pattern

javascript - JS Keydown 在第一个事件之后触发事件之前有一些奇怪的 1 秒延迟

javascript - Vue.js 不会使用 v-for 重新渲染组件

javascript - 使用vuejs动态设置id标签

html - 如何 v-model 2 值?

javascript - 使用 Vue.js 将 v-if 构造为 v-for 内部的过滤器时出现问题

javascript - 找到两点之间 Angular 最快方法

javascript - Java 和 JavaScript 中的不同 md5 哈希结果

javascript - Electron JS-无法解构 'BrowserWindow'的 'require(…).remote'属性,因为它未定义

node.js - 为 Vue 应用程序前端和 Node.js 后端配置 nginx