Error in mounted hook: “TypeError: Cannot read property ‘on‘ of null“

报错提示:

 在运行VUE项目的时候出现了以上错误,错误原因是由于better-scroll还未挂载就使用了其on方法。代码如下:

<template>
  <div class="wrappers" ref="wrappers">
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  name: "Scroll",
  data() {
    return {
      scroll: null,
      message: "hahaha",
    };
  },
  props: {
    probeType: {
      type: Number,
      default: 0,
    },
    //上拉加载更多
    pullUpLoad: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    //1.创建better-scroll对象
    this.$nextTick(() => {
      this.scroll = new Bscroll(this.$refs.wrappers, {
        pobeType: this.pobeType,
        click: true,
        pullUpLoad: this.pullLoad, //是否上拉加载更多
      });

      //3监听是否滚动到底部
    });

    //2.监听better-scroll的滚动位置
    if (this.probeType > 2) {
      this.scroll.on("scroll", function (position) {
        this.$emit("scroll", position);
      });
    }
  },
};
</script>

<style lang="less" scoped>
</style>

解决办法:

将最后几行代码放入this.$nextTick()中。代码如下:

<template>
  <div class="wrappers" ref="wrappers">
    <div class="content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
export default {
  name: "Scroll",
  data() {
    return {
      scroll: null,
      message: "hahaha",
    };
  },
  props: {
    probeType: {
      type: Number,
      default: 0,
    },
    //上拉加载更多
    pullUpLoad: {
      type: Boolean,
      default: false,
    },
  },
  mounted() {
    //1.创建better-scroll对象
    this.$nextTick(() => {
      this.scroll = new Bscroll(this.$refs.wrappers, {
        pobeType: this.pobeType,
        click: true,
        pullUpLoad: this.pullLoad, //是否上拉加载更多
      });
      //2.监听better-scroll的滚动位置
      if (this.probeType > 2) {
        this.scroll.on("scroll", function (position) {
          this.$emit("scroll", position);
        });
      }
      //3监听是否滚动到底部
    });
  },
};
</script>

<style lang="less" scoped>
</style>

以上就是问题的解决,如果觉得不错别忘了点个赞哦^_^。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值