如何临时化< input>的分析.场地? [英] How to temporize the analysis of an <input> field?

查看:39
本文介绍了如何临时化< input>的分析.场地?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在没有用户活动时分析< input> 字段的内容.

I would like to analyze the content of an <input> field when there is no user activity.

下面我将举一个简单的示例(计算字符数),但是实际分析是否非常昂贵,因此我希望在用户不活动时分批进行操作,而不是每次更改时都进行操作绑定变量.

I will take below a simple example (counting the number of characters) but the actual analysis if very expensive so I would like to do it in batches, when there is some inactivity of the user instead of doing it at every change of the bound variable.

用于直接分析的代码可能是

The code for the straightforward analysis could be

var app = new Vue({
  el: '#root',
  data: {
    message: ''
  },
  computed: {
    // a computed getter
    len: function() {
      // `this` points to the vm instance
      return this.message.length
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script>
<div id="root">
  <input v-model="message">Length: <span>{{len}}</span>
</div>

我的问题是,每次更改 message 时,都会调用 function().是否有内置的机制来限制查询,还是在JS中解决此类问题的典型方法?

My problem is that function() is called at each change of message. Is there a built-in mechanism to throttle the query, or a typical approach to such a problem in JS?

推荐答案

可以按照预期的方式运行.正如文档中所述:

That works the way it is supposed to. As it is said in the docs:

当原始数据更改时,它将更新依赖于计算属性的所有绑定

It will update any bindings that depend on computed property when the original data changes

但是有一种方法可以做到:

But there's a way to do it:

var app = new Vue({
  el: '#root',
  data: {
    message: '',
    messageLength:  0
  },
  methods: {
    len: _.debounce(
      function() {
        this.messageLength = this.message.length
      }, 
      300 // time
    )
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script>
<script src="https://unpkg.com/underscore@1.8.3"></script> <!-- undescore import -->
<div id="root">
  <input v-model="message" v-on:keyup="len">Length: <span>{{ messageLength }}</span>
</div>

完整示例: https://vuejs.org/v2/guide/computed.html#Watchers

p.s.关于 compute 正在与 vue 的作者同步的评论:

p.s. A comment about computed being sync from the vue's author: https://forum-archive.vuejs.org/topic/118/throttle-computed-properties/3

pps 经典文章关于反跳之间的区别code>和油门.

p.p.s Classics article about difference between debounce and throttle.

这篇关于如何临时化&lt; input&gt;的分析.场地?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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