【问题标题】:VueJS: setInterval method not working properlyVueJS:setInterval 方法无法正常工作
【发布时间】:2018-10-16 21:07:46
【问题描述】:

请告诉我我做错了什么?我想每 2 秒激活一次“布料”更新。还在学习vue。谢谢

    data() {
        return {
            clothes: ['t-shirts', 'sneakers', 'jackets'],
            count: 0,
            cloth: ''
        }
    },
    methods: {
        startInterval() {
            setInterval(() => {

                this.cloth = this.clothes[this.count]
                this.count++
                if (this.count >= this.clothes.length) {
                    this.count = 0;
                }
            }, 2000)
        }
    }

【问题讨论】:

  • 你在哪里执行startInterval
  • 哦..没错..如果我使用 startInterval 添加事件点击,它就可以工作。但是如何让这个函数自动运行呢?

标签: vue.js vuejs2 setinterval


【解决方案1】:

Vue 有一个生命周期,您可以利用它来完成这个目标。您可以挂钩created 函数并在以下范围内执行您的时间间隔:

created() {
    this.startInterval()
},

这是not 一种方法。它将是您的 datamethod 属性的 sibling

【讨论】:

  • 谢谢!它有帮助
猜你喜欢
  • 2019-06-02
  • 2021-12-29
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
相关资源
最近更新 更多