在 vue/nuxt 中离开路线时清除超时

问题描述 投票:0回答:1

我有一个功能,应该每隔几秒更改一次单词。到目前为止一切顺利,一旦我改变路线我想清除超时功能,因为我在下一页上得到以下错误: 75:1

我在

clearTimeout(randomizeText)

中用
onBeforeRouteLeave
试过,但这不起作用。

<span ref="word"></span>
onMounted(() => {
  randomizeText()
  setInterval(randomizeText, 4000)
})

onBeforeRouteLeave(() => {
  clearTimeout(randomizeText)
})

const word = ref(null)
const words = reactive(['Word-1', 'Word-2'])
let i = 0

function randomizeText() {
  i = randomNum(i, words.length)
  const newWord = words[i]

  setTimeout(() => {
    word.value.textContent = newWord
  }, 200) // time to allow opacity to hit 0 before changing word
}

function randomNum(num, max) {
  let j = Math.floor(Math.random() * max)

  // ensure diff num every time
  if (num === j) {
    return randomNum(i, max)
  } else {
    return j
  }
}
    
javascript vue.js nuxt.js vuejs3 nuxtjs3
1个回答
0
投票
将您的代码更改为此,以记住对超时的引用,然后在路由更改时将其清除:

let timeout onMounted(() => { randomizeText() setInterval(randomizeText, 4000) }) onBeforeRouteLeave(() => { clearTimeout(timeout) }) const word = ref(null) const words = reactive(['Word-1', 'Word-2']) let i = 0 function randomizeText() { i = randomNum(i, words.length) const newWord = words[i] timeout = setTimeout(() => { word.value.textContent = newWord }, 200) // time to allow opacity to hit 0 before changing word } function randomNum(num, max) { let j = Math.floor(Math.random() * max) // ensure diff num every time if (num === j) { return randomNum(i, max) } else { return j } }
    
© www.soinside.com 2019 - 2024. All rights reserved.