如何在Vue(Nuxt js)中以5秒的间隔更改随机文本

Rah*_*nto 3 javascript vue.js nuxt.js

我是 Vue 的初学者,在页面加载时以 5 秒的间隔更改随机文本时遇到一些问题。

<template>
  <section class="container">
      <h1 class="title">
        Welcome {{ whois }}
      </h1>
	</section>
<template>

<script>
export default {
  data() {
    return {
      whois: ['Student', 'Developer', 'Programmer']
    }
  },
  // methods: {
  //   randomWhois(){
      
  //   }
  // },
  // beforeMount() {
  //   this.randomWhois();
  // }
}
</script>
Run Code Online (Sandbox Code Playgroud)

我希望当间隔5秒时,我的文字总是改变。

示例:(总是在 5 秒内更改)


欢迎学生

欢迎开发者

欢迎程序员


非常感谢!

rye*_*oss 9

在 中mounted,设置每 5 秒触发一次方法的时间间隔。此方法只会将whois数组向左移动。然后在模板中,更改Welcome以显示数组中的第一个元素{{ whois[0] }}

<template>
  <section class="container">
      <h1 class="title">
        Welcome {{ whois[0] }}
      </h1>
    </section>
<template>

<script>
export default {
  data() {
    return {
      whois: ['Student', 'Developer', 'Programmer']
    }
  },
  mounted(){
    window.setInterval(()=>{
      this.pollPerson();
    }, 5000);

  },
  methods: {
    pollPerson(){
      const first = this.whois.shift();
      this.whois = this.whois.concat(first);
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)