用 setInterval 替换 vue.js 模板 [英] Replacing vue.js template with setInterval

查看:27
本文介绍了用 setInterval 替换 vue.js 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 vue.js 以给定的时间间隔刷新 div 的内容,但到目前为止几乎没有成功.这是我目前所拥有的:

var vm = new Vue({el: '#feature',模板:'<div id={{content}}></div>',数据:功能列表:[{内容:'一个'}, {内容:'b'}, {内容:'c'}]}});

在我的 html 上,我有以下内容:

我的方法是遍历这个数组并以给定的间隔替换模板中的内容.问题是我不知道该怎么做.

这是我尝试作为在 data 中使用数组的替代方法:使用 setter 函数使 content 成为计算属性,在 中使用单个字符串数据.像这样:

var vm = new Vue({el: '#feature',模板:'<div id={{content}}></div>',数据: {内容:'一个'},计算:{设置模板:{设置:函数(新值){var 值 = 新值this.content = 值}}}});vm.setTemplate = 'c'

(jsfiddle 此处)

现在,我该怎么走?如何从一组给定的字符串中以特定间隔更改内容?

解决方案

我认为你可以使用 生命周期钩子,特别是 ready 钩子:

var vm = new Vue({el: '#feature',模板:'<div id={{content}}>{{content}}</div>',数据: {内容:'你好',特征:['a','b','c'],当前索引:0},创建:函数(){var self = this设置超时(函数循环(){self.content = self.features[self.currentIndex++]self.currentIndex %= self.features.length设置超时(周期,2000)}, 2000)}});

请参阅更新后的小提琴.

I've been trying to refresh the content of a div at a given interval using vue.js, but up until now have had little if no success. Here's what I have at this point:

var vm = new Vue({
    el: '#feature',
    template: '<div id={{content}}></div>',
    data:
        featureList: [{
            content: 'a'
        }, {
            content: 'b'
        }, {
            content: 'c'
        }]
    }
});

On my html, I've the following:

<div id="feature"></div>

My approach here is to iterate through this array and replace content in the template at a given interval. The problem is that I'm not sure how to do it.

This is what I tried as an alternative to having an array in data: making content a computed property with a setter function, with a single string in data. Like this:

var vm = new Vue({
  el: '#feature',
  template: '<div id={{content}}></div>',
  data: {
    content: 'a'
  },
  computed: {
    setTemplate: {
      set: function(newValue) {
      var values= newValue
      this.content = values
      }
    }
  }
});

vm.setTemplate = 'c'

(jsfiddle here)

Now, how do I go from here? How do I change content at a certain interval from a set of given strings?

解决方案

I think you can use the lifecycle hooks for this, specifically the ready hook:

var vm = new Vue({
    el: '#feature',
    template: '<div id={{content}}>{{content}}</div>',
    data: {
        content: 'hi there',
        features: ['a', 'b', 'c'],
        currentIndex: 0
    },

    created: function() {
        var self = this
        setTimeout(function cycle() {
            self.content = self.features[self.currentIndex++]
            self.currentIndex %= self.features.length
            setTimeout(cycle, 2000)
        }, 2000)
    }
});

See the updated fiddle.

这篇关于用 setInterval 替换 vue.js 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆