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

标签 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>

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

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


欢迎学生

欢迎开发者

欢迎程序员


非常感谢!

最佳答案

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>

关于javascript - 如何在 Vue(Nuxt js)中以 5 秒的间隔更改随机文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54770812/

相关文章:

javascript - CollapsiblePanelExtender 点击事件

javascript - 我应该将 '[]' 附加到多个 html 复选框吗?

javascript - Vuex 突变 mutate 不 react

JavaScript 正则表达式文字在函数调用之间持续存在

javascript - 测试未使用 casperJS 执行

javascript - 在 v-navigation-drawer 关闭的情况下加载网站

vue.js - 结果缺少 allposts 属性

javascript - vue.js中如何触发元素?

nuxt.js 热重载很慢

javascript - Bootstrap 5 Nuxt 动态组件不工作