VUE 关于$nextTick的问题

小key
  • 72

created() {

  this.$http.get('/api/goods').then((response) => {
    response = response.body;
    if (response.errno === ERR_OK) {
      this.goods = response.data;     
    }
  });
        this.$nextTick(() => {
        this._initScroll();
      });
},
methods: {
  _initScroll() {
    this.meunScroll = new BScroll(this.$els.menuWrapper, {});
    this.foodsScroll = new BScroll(this.$els.foodsWrapper, {});
  }
}
    调用better-scroll插件报错;但是把this.$nextTick放进if里面就没有问题,
    既然$nextTick是在dom加载完再执行那应该随便放哪儿都行啊?
    初学vue,希望有人指点

这是报错内容
Uncaught (in promise) TypeError: bscroll.min.js?c4f9:1
Cannot read property 'style' of undefined

at new e (eval at <anonymous> (http://localhost:8080/app.js:733:2), <anonymous>:1:1609)
at VueComponent._initScroll (eval at <anonymous> (http://localhost:8080/app.js:703:2), <anonymous>:46:26)
at VueComponent.eval [as _initScroll] (eval at <anonymous> (http://localhost:8080/app.js:606:2), <anonymous>:216:72)
at VueComponent.eval (eval at <anonymous> (http://localhost:8080/app.js:703:2), <anonymous>:38:13)
at Array.func (eval at <anonymous> (http://localhost:8080/app.js:606:2), <anonymous>:491:10)
at nextTickHandler (eval at <anonymous> (http://localhost:8080/app.js:606:2), <anonymous>:447:16)
回复
阅读 10.1k
1 个回答

this.$nextTick是在下次DOM更新循环结束时调用延迟回调函数。
事实上,你第一次从后端获取数据,你页面DOM首次加载完也会执行这个函数
你从后端获取数据本身就是个异步事件,你要在拿到数据之后调用$nextTick这个方法,就不会报错,正如你写在if里面,只要满足 ....then((response) => {

// 写在这里就可以

}
写在then(..)方法之外就不行了了,因为在异步队列中$nextTick的优先级高,所以你总会拿不到的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏