我似乎无法去抖(lodash)计算属性或vuex getter。去抖动函数总是返回undefined。
https://jsfiddle.net/guanzo/yqk0jp1j/2/
HTML:
<div id="app">
<input v-model="text">
<div>computed: {{ textComputed }} </div>
<div>debounced: {{ textDebounced }} </div>
</div>
JS:
new Vue({
el:'#app',
data:{
text:''
},
computed:{
textDebounced: _.debounce(function(){
return this.text
},500),
textComputed(){
return this.text
}
}
})
答案 0 :(得分:15)
正如我在评论中提到的,debouncing是一种固有的异步操作,因此无法返回值。根据您的需要,您可能希望在输入方面进行辩护。 text
中的值与textComputed
中的值没有区别,但如果您v-model="textComputed"
,则值设置将被去抖动。
如果您特别想要一个变量的去抖动版本, mrogers 已经给出了一个很好的解决方案。
var x = new Vue({
el: '#app',
data: {
text: 'start'
},
computed: {
textComputed: {
get() {
return this.text;
},
set: _.debounce(function(newValue) {
this.text = newValue;
}, 500)
}
}
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<div id="app">
<div>
Debounced input:
<input v-model="textComputed">
</div>
<div>
Immediate input:
<input v-model="text">
</div>
<div>computed: {{ textComputed }} </div>
<div>debounced: {{ text }} </div>
</div>
答案 1 :(得分:1)
我没有任何关于为什么debounce函数不能对计算属性起作用的见解。但是,另一种解决方案是将去抖动放在methods
部分的函数中,并通过watch
调用它。
https://jsfiddle.net/vsc4npv3/
HTML:
<div id="app">
<input v-model="text">
<div>computed: {{ textComputed }} </div>
<div>debounced: {{ debouncedText }} </div>
</div>
JavaScript的:
var x = new Vue({
el:'#app',
data:{
text:'',
debouncedText: ''
},
watch: {
text: function (val) {
this.debouncer();
}
},
computed:{
textComputed(){
return this.text;
}
},
methods: {
debouncer: _.debounce(function(){
this.debouncedText = this.text;
},500)
}
})
答案 2 :(得分:1)
_.debounce
)import Vue from 'vue'
// Thanks to https://github.com/vuejs-tips/v-debounce/blob/master/debounce.js
function debounce(fn, delay) {
var timeoutID = null
return function () {
clearTimeout(timeoutID)
var args = arguments
var that = this
timeoutID = setTimeout(function () {
fn.apply(that, args)
}, delay)
}
}
function debouncedProperty(delay) {
let observable = Vue.observable({ value: undefined });
return {
get() { return observable.value; },
set: debounce(function (newValue) { observable.value = newValue; }, delay)
}
}
// component
export default {
computed: {
myProperty: debouncedProperty(300),
},
}