vue.js - mounted 方法在加载数据之前被触发 - VueJS

标签 vue.js lifecycle vue-resource

我正在使用 Vue Resource从 REST API 检索图像集合。请求在我的 Vue 组件的 created Hook 中发送。

问题是,我试图在 mounted Hook 中访问检索到的数据,但数据未加载。

我在控制台中收到此错误:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"

这是我的组件:

<script>
export default {
  data() {
    return { imgs : '' };
  },
  created() {
    // the full url is declare in my main.js
    this.imgs = this.$resource('acf/v3/pages/4');

    this.imgs.query().then((response) => {
      console.log('success', response);
      this.imgs = response.data.acf.gallery;
    }, (response) => {
      console.log('erreur', response);
    });
  },
  mounted() {
    // get the ref="image" in my dom template
    let imgs = this.$refs.image;

    imgs.forEach((img) => {
      // I do some stuff with imgs
    });
  }
}
</script>

如果我将 setTimeout 包裹在 mounted 的内容周围,一切正常。

所以,我不明白如何在执行 mounted Hook 之前等待我的数据加载。这不就是 Vue 生命周期钩子(Hook)的作用吗?

最佳答案

由于 this.imgs.query() 调用是异步的,您的 mounted Hook 在 then 处理程序设置 this.imgs(我假设它与 v-for 绑定(bind)到模板中具有属性 ref="image" 的元素).因此,即使组件已挂载到 DOM,$refs 仍未设置。

我会创建一个方法来“用 imgs 做一些事情”,然后在 $nextTick callback 中调用该方法在异步调用的 then 处理程序中。传递给 $nextTick 的回调将“在下一个 DOM 更新周期后执行”,这意味着 $refs 将在此时设置。

<script>
export default {
  data() {
    return { imgs: '' };
  },
  created() {
    // the full url is declare in my main.js
    this.imgs = this.$resource('acf/v3/pages/4');

    this.imgs.query().then((response) => {
      console.log('success', response);
      this.imgs = response.data.acf.gallery;
      this.$nextTick(() => this.doStuffWithImgs());
    }, (response) => {
      console.log('erreur', response);
    });
  },
  methods: {
    doStuffWithImgs() {
      // get the ref="image" in my dom template
      let imgs = this.$refs.image;

      imgs.forEach((img) => {
        // I do some stuff with imgs
      });
    }
  }
}
</script>

关于vue.js - mounted 方法在加载数据之前被触发 - VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717415/

相关文章:

javascript - Mocha 与 Vue : Resolution method is overspecified

javascript - 有什么方法可以使用 testcafe 上传文件夹吗?

vue.js - `This` 在 vue.js 观察器中未定义

javascript - 在 Vue.js2 中使用哪个生命周期 Hook 在页面加载时调用函数?

javascript - 基本 vue.js 2 和 vue-resource http get 变量赋值

vue-resource - 如何在 Vue 实例的 beforeCreate Hook 中进行异步调用?

vue.js - Vue 模板中是否可以有动态元素名称?

visual-studio - 使用 Visual Studio 自动部署 VueJS

java - Maven 目标未附加到阶段

javascript - react native : sending events from android to javascript