javascript - 如何使用 Vue.js 类设置计时器

标签 javascript jquery vue.js

我只是使用 Vue.js 来更新我正在搞乱的网站上的帖子,这就是我到目前为止所得到的(我仍在学习 javascript,并且不太擅长)

[app.js]

var Vue = require('vue');

Vue.use(require('vue-resource'));

var app = new Vue({

  el: '#app',

  components: {
    'postlist' : require('./components/postlist/postlist.js')
  }

});

[poSTList.js]

module.exports = {

  template: require('./postlist.template.html'),

  data: function () {
    return {
      'search': '',
      'posts' : {}
    }
  },

  methods: {
    'updatePosts' : function()
    {
      this.$http.get('api/posts', function(responce, status, request)
      {
        this.$set('posts', responce.data);
      });
    }
  }
};

我正在寻找的是让 updatePosts 每 x 秒触发一次,我该怎么做?

我试过在 app.js

中这样做
setInterval(function()
{
  app.components.postlist.methods.updatePosts(); // doesnt work
  app.postlist.updatePosts(); //doesnt work either
}, 500);

并尝试将 setInterval 放入组件本身

我对此很迷茫,实现这一目标的最佳方法是什么?

updatePosts 每 x 秒运行一次?

最佳答案

我也遇到了 Vue 中范围的问题。

这应该可行

module.exports = {
  template: require('./postlist.template.html'),
  data: function () {
    return {
      'search': '',
      posts: {}
    }
  },
  methods: {
    updatePosts: function () {
      var self = this;
      self.$http.get('api/posts', function(responce, status, request) {
        self.posts = responce.data;
        setTimeout(function(){ self.updatePosts() }, 2000);
      });
    }
  },
  created: function () {
    this.updatePosts();
  }
}

Vue 中的函数的工作方式有点不同,因为您的方法 updatePosts 不是常规函数。它是在 $vm.methods 对象中定义的函数。所以不能像setTimeout($vm.updatePosts)那样定期调用。实际上 $vm.updatePosts 并不存在。如果你像 $vm.updatePosts() 这样调用它,那就是另一回事了。 $vm 实例自动调用它的方法...所以正确的方法是 setTimeout(function(){ self.updatePosts() },2000)

关于javascript - 如何使用 Vue.js 类设置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065828/

相关文章:

javascript - 如何在 Angular 4 上获取引荐来源网址?

javascript - 使用javascript从日期数组中查找最大日期

javascript - 使用 javascript/jquery 准确滚动到 DIV 元素的最佳方法是什么

php - jQuery/PHP - 延迟加载画廊不断尝试获取图像,即使它们已经全部加载

vue.js - 如何解决Vue.js中的 "Adjacent JSX elements must be wrapped in an enclosing tag"问题

javascript - 如何在 html ref 标签中获取谷歌应用程序脚本函数/变量

javascript - 表格为空时 Flask Modal 不工作

javascript - 未捕获的 TypeError : Object [object Object] has no method 'replace' with backbone. js 和 CoffeeScript

javascript - 为什么在 Vue 中从数组中删除元素时会在最后一个索引处发生转换?

html - 使用vue js减少小数位数并添加逗号