定时器setinterval函数+数据页面渲染

为什么不能将数据渲染到页面上


```html
<template>
  <p v-html="state"></p>
  <button @click="asd">切换</button>
 </template>
     
 <script>
 export default {
   data() {
     return {
       state:"问题接收"
     };
   },
   methods: {
     asd(){
       let states= [ "问题解析", "发送给ChatGPT", "等待ChatGPT回答"]
       let i=0
       const timeTop = setInterval(function () {
         this.state=states[i]
         console.log(this.state)
         i++
         if (i >=states.length) {
           clearInterval(timeTop);
         }
         
       }, 1000);
     }
   },
 
 };
 </script>

img

但是把定时器里的函数,换成箭头函数的话数据就会成功渲染(请问是什么原因)

img


```

this指向的问题,使用function的话this指向的是计时器,使用箭头函数this指向的是计时器的上一级,也就是vue

this指向改变了用箭头函数


 const timeTop = setInterval(()=> {
         this.state=states[i]
         console.log(this.state)
         i++
         if (i >=states.length) {
           clearInterval(timeTop);
         }
         
       }, 1000);

【以下回答由 GPT 生成】

Markdown格式的答案:

问题解析

在Vue.js中使用setInterval函数定时刷新数据页面渲染时,使用箭头函数和普通函数的差异导致了数据无法渲染到页面上的问题。

解决方案

Vue.js的数据绑定使用了响应式系统,当数据发生改变时,会自动更新到页面上。然而,在定时器的回调函数中,普通函数的this上下文指向了定时器函数本身,而不是Vue实例。因此,普通函数无法访问到Vue实例中的data数据,导致数据无法渲染到页面上。

解决这个问题有以下几种方式:

方案一:使用箭头函数

箭头函数不会改变this指向,它会继承父级作用域的this。因此,在箭头函数中可以访问到Vue实例中的data数据,数据会成功渲染到页面上。

toggle() {
  let states = ["问题解析", "发送给ChatGPT", "等待ChatGPT回答"];
  let i = 0;
  const timer = setInterval(() => {
    this.state = states[i];
    console.log(this.state);
    i++;
    if (i >= states.length) {
      clearInterval(timer);
    }
  }, 1000);
}

方案二:使用bind绑定this

使用bind方法可以将回调函数的this绑定到Vue实例上,使得回调函数中的this指向Vue实例。

toggle() {
  let states = ["问题解析", "发送给ChatGPT", "等待ChatGPT回答"];
  let i = 0;
  const timer = setInterval(function() {
    this.state = states[i];
    console.log(this.state);
    i++;
    if (i >= states.length) {
      clearInterval(timer);
    }
  }.bind(this), 1000);
}

方案三:使用箭头函数或普通函数,并保存this指向

在定时器的回调函数中,可以先将this指向保存到一个变量中,在回调函数中使用该变量来访问Vue实例中的data数据。

toggle() {
  let states = ["问题解析", "发送给ChatGPT", "等待ChatGPT回答"];
  let i = 0;
  const self = this;
  const timer = setInterval(function() {
    self.state = states[i];
    console.log(self.state);
    i++;
    if (i >= states.length) {
      clearInterval(timer);
    }
  }, 1000);
}

以上三种方案都可以解决数据无法渲染到页面上的问题,具体选择哪种方案可以根据实际需求和个人喜好来决定。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^