【问题标题】:clear intervals and timeouts on nuxt.js build清除 nuxt.js 构建的间隔和超时
【发布时间】:2019-05-29 00:51:07
【问题描述】:

在我的网站上,我为轮播等设置了一些间隔和超时。现在我在组件destroyed()生命周期钩子上清除它们。但我仍然收到此构建警告。

这是我的组件之一的示例

<script>
  data() {
    return {
      carouselInterval: null
    }
  },
  created() {
    this.startInterval();
  },
  methods: {
    startInterval() {
      this.carouselInterval = setInterval(() => {
         ...
      }, 5000);
    }
  },
  destroyed() {
    clearInterval(this.carouselInterval);
  }
</script>

我也有这样的timeOut

<script>
  data() {
    return {
      testTimeout: null
    }
  },
  created() {
    this.startTimeout();
  },
  methods: {
    startTimeout() {
      this.testTimeout = setTimeout(() => {
         ...
      }, 5000);
    }
  },
  destroyed() {
    clearTimeout(this.testTimeout);
  }
</script>

现在我假设这会清除这些计时功能,但我仍然收到此警告。

我做错了什么吗?还有其他方法可以清除构建时的所有计时功能吗?

编辑

我 100% 确定我已经清理了 destroyed() 生命周期挂钩上的所有计时函数

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js


    【解决方案1】:

    destroyed() 生命周期挂钩在使用 SSR 时不会被调用。你可以在这里阅读更多关于这个SSR component lifecycle hooks

    这意味着您不能使用它来清除服务器上的超时。

    您可以通过将区间函数移动到在 mounted()beforeMount() 生命周期挂钩中调用来解决此问题,因为它们仅在客户端调用。

    在您的示例中,您可以将代码更改为

    <script>
      data() {
        return {
          carouselInterval: null
        }
      },
      mounted() {
         this.startInterval();
      },
      methods: {
        startInterval() {
          this.carouselInterval = setInterval(() => {
             ...
          }, 5000);
        }
      }
    </script>
    

    这将防止nuxt.js 构建超时。

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多