在加载数据之前触发挂载方法 - VueJS

Bro*_*nBe 8 lifecycle vue.js vue-resource

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

问题是,我正在尝试访问mounted钩子中检索到的数据,但是没有加载数据.

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

[Vue警告]:挂钩时出错:"TypeError:无法读取属性'forEach'未定义"

这是我的组件:

<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>
Run Code Online (Sandbox Code Playgroud)

如果我把setTimeout内容包裹起来mounted,一切正常.

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

tha*_*ksd 6

由于this.imgs.query()调用是异步的,mounted因此将在then处理程序设置之前调用您的钩子this.imgs(我假设该钩子已绑定v-for到具有属性的模板中的元素ref="image")。因此,即使组件已安装到DOM上,$refs也尚未设置。

我将创建一个“用img做一些事情”的方法,然后在异步调用的处理程序中的$nextTick回调中调用该方法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>
Run Code Online (Sandbox Code Playgroud)