Vue computed property not recomputing as I would have expected - vue.js

I'm trying to create a generic search component with an event that gets emitted with the search string back to the parent so the parent can actually filter the results.
With the code below why does computed.filteredDocuments not recompute when the value of this.searchCriteria changes and how can I tweak my code so that it does recompute when updatedSearchString is called?
Parent component
<template>
<search :searchCriteria="searchCriteria" #searchString="updatedSearchString" />
<div v-for="(doc, index) in filteredDocuments" v-bind:key="index">
<div>{{doc.filename}}</div>
</div>
</template>
<script>
import store from '../store/index'
import { mapState } from 'vuex'
// import _ from 'lodash'
import Search from '../components/search'
export default {
name: 'Parent',
components: {
Search: Search
},
data () {
return {
searchCriteria: ''
}
},
computed: {
...mapState({
documents: state => state.documents.items
}),
filteredDocuments () {
console.log('in computed')
return _(this.documents)
.filter(this.applySearchFilter)
.value()
}
},
methods: {
updatedSearchString (searchString) {
this.searchCriteria = searchString <-- I WOULD HAVE EXPECTED BY UPDATING THIS IT WOULD TRIGGER COMPUTED.FILTEREDDOCUMENTS TO RECOMPUTE
}
},
applySearchFilter (doc) {
console.log('in applySearchFilter')
// If no search criteria return everything
if (this.searchCriteria === null) {
return true
}
if (doc.filename.toLowerCase().includes(this.searchCriteria.toLowerCase())) {
return true
}
return false
}
}
</script>
Child component
<template>
<div>
<q-search v-model="search" placeholder="Search" />
</div>
</template>
<script>
export default {
name: 'Search',
props: {
searchCriteria: { type: String, required: true }
},
data () {
return {
search: null
}
},
mounted () {
this.search = this.searchCriteria // Clone
},
watch: {
search: function (newVal, oldVal) {
// If no search criteria return everything
if (!newVal) {
this.clearSearch()
}
this.$emit('searchString', newVal) <-- THIS EMITS THE SEARCH VALUE TO THE PARENT
}
}
}
</script>

What I ran into turning your example code into a snippet was some of the camel case/kebab case issue: HTML is case-insensitive, so the event should be kebab-case, not camelCase. This example filters as expected.
new Vue({
el: '#app',
data: {
searchCriteria: '',
documents: [{
filename: 'FirstFile'
},
{
filename: 'SecondFile'
},
{
filename: 'LastOne'
}
]
},
methods: {
updatedSearchString(searchString) {
this.searchCriteria = searchString
},
applySearchFilter(doc) {
console.log('in applySearchFilter')
// If no search criteria return everything
if (this.searchCriteria === null) {
return true
}
if (doc.filename.toLowerCase().includes(this.searchCriteria.toLowerCase())) {
return true
}
return false
}
},
computed: {
filteredDocuments() {
console.log('in computed')
return this.documents
.filter(this.applySearchFilter)
}
},
components: {
search: {
template: '#child-template',
props: {
searchCriteria: {
type: String,
required: true
}
},
computed: {
search: {
get() {
return this.searchCriteria;
},
set(value) {
this.$emit('search-string', value);
}
}
}
}
}
});
<link href="https://unpkg.com/quasar-extras#latest/material-icons/material-icons.css" rel="stylesheet"/>
<script src="https://unpkg.com/vue#latest/dist/vue.js"></script>
<link rel="stylesheet" type="text/css" href="https://unpkg.com/quasar-framework#latest/dist/umd/quasar.mat.min.css">
<script src="https://unpkg.com/quasar-framework#latest/dist/umd/quasar.mat.umd.min.js"></script>
<div id="app">
<search :search-criteria="searchCriteria" #search-string="updatedSearchString"></search>
<div v-for="(doc, index) in filteredDocuments" v-bind:key="index">
<div>{{doc.filename}}</div>
</div>
</div>
<template id="child-template">
<div>
<q-search v-model="search" placeholder="Search" />
</div>
</template>

Related

Toggle button component how to reset from parent

There is a toggle component, which I connect to the parent. Found a bug, haven't found a solution yet.
toggle-button
<template>
<label :for='id + "_button"' :class='{"active": isActive}' class='toggle__button'>
<input type='checkbox' :id='id + "_button"' v-model='checkedValue'>
<span class='toggle__switch'></span>
</label>
</template>
<script>
export default ({
props: {
defaultState: {
type: Boolean,
default: false
},
id: {
type: String,
default: 'primary'
}
},
data() {
return {
currentState: this.defaultState
};
},
computed: {
isActive() {
return this.currentState;
},
checkedValue: {
get() {
return this.defaultState;
},
set(newValue) {
this.currentState = newValue;
this.$emit('change', newValue);
}
}
},
methods: {
reset() {
this.currentState = false ;
}
}
});
</script>
how can i succinctly make a reset button? I use this option now, but after reset, when I click on toggle, it does not work the first time.
<button
#click='
$refs.toggleOriginal.reset($event),
$refs.toggleAnalog.reset($event),
$refs.toggleAvailable.reset($event)
'
>
reset
</button>
Each toggle has ref in parent.
I think what you may be saying is that you have a toggle button that can flip a value anywhere (perhaps stored in a higher state?) and a reset button that can set the value back to it's initial default.
Keep the management of this data property handled outside of toggle, and make toggle responsible for simply flipping the value, and reset responsible for resetting it.
Here is what I would do:
// parent.vue
<template>
<div>
Toggled value: {{toggleValue}}
<resetButton v-model="toggleValue" />
<toggleButton v-model="toggleValue" />
</div>
</template>
<script>
export default {
data() {
return {
toggleValue: false,
}
}
}
</script>
// toggleButton.vue
<template>
<button #click="toggle">Toggle</button>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
}
},
computed: {
toggleValue: {
get() {
return this.value;
},
set(val) {
this.$emit('input', val);
}
}
},
methods: {
toggle() {
this.toggleValue = !this.toggleValue
}
}
}
</script>
// resetButton.vue
<template>
<button #click="reset">Reset</button>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
}
},
methods: {
reset() {
this.$emit('input', false);
}
}
}
</script>

VueJS input with v-model breaks the user input [duplicate]

I have a simple input box in a Vue template and I would like to use debounce more or less like this:
<input type="text" v-model="filterKey" debounce="500">
However the debounce property has been deprecated in Vue 2. The recommendation only says: "use v-on:input + 3rd party debounce function".
How do you correctly implement it?
I've tried to implement it using lodash, v-on:input and v-model, but I am wondering if it is possible to do without the extra variable.
In template:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
In script:
data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
The filterkey is then used later in computed props.
I am using debounce NPM package and implemented like this:
<input #input="debounceInput">
methods: {
debounceInput: debounce(function (e) {
this.$store.dispatch('updateInput', e.target.value)
}, config.debouncers.default)
}
Using lodash and the example in the question, the implementation looks like this:
<input v-on:input="debounceInput">
methods: {
debounceInput: _.debounce(function (e) {
this.filterKey = e.target.value;
}, 500)
}
Option 1: Re-usable, no deps
- Recommended if needed more than once in your project
/helpers.js
export 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)
}
}
Typescript?
export function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): T {
let timeoutID: number | null = null;
return function (this: any, ...args: any[]) {
clearTimeout(timeoutID);
timeoutID = setTimeout(() => {
fn.apply(this, args);
}, delay);
} as T;
}
Or if using a d.ts:
declare function debounce(fn: (...args: any[]) => void, delay: number): (...args: any[]) => void;
/Component.vue
<script>
import {debounce} from './helpers'
export default {
data () {
return {
input: '',
debouncedInput: ''
}
},
watch: {
input: debounce(function (newVal) {
this.debouncedInput = newVal
}, 500)
}
}
</script>
Codepen
Option 2: In-component, also no deps
- Recommended if using once or in small project
/Component.vue
<template>
<input type="text" v-model="input" />
</template>
<script>
export default {
data: {
timeout: null,
debouncedInput: ''
},
computed: {
input: {
get() {
return this.debouncedInput
},
set(val) {
if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.debouncedInput = val
}, 300)
}
}
}
}
</script>
Codepen
Assigning debounce in methods can be trouble. So instead of this:
// Bad
methods: {
foo: _.debounce(function(){}, 1000)
}
You may try:
// Good
created () {
this.foo = _.debounce(function(){}, 1000);
}
It becomes an issue if you have multiple instances of a component - similar to the way data should be a function that returns an object. Each instance needs its own debounce function if they are supposed to act independently.
Here's an example of the problem:
Vue.component('counter', {
template: '<div>{{ i }}</div>',
data: function(){
return { i: 0 };
},
methods: {
// DON'T DO THIS
increment: _.debounce(function(){
this.i += 1;
}, 1000)
}
});
new Vue({
el: '#app',
mounted () {
this.$refs.counter1.increment();
this.$refs.counter2.increment();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
<div id="app">
<div>Both should change from 0 to 1:</div>
<counter ref="counter1"></counter>
<counter ref="counter2"></counter>
</div>
Very simple without lodash
handleScroll: function() {
if (this.timeout)
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
// your action
}, 200); // delay
}
I had the same problem and here is a solution that works without plugins.
Since <input v-model="xxxx"> is exactly the same as
<input
v-bind:value="xxxx"
v-on:input="xxxx = $event.target.value"
>
(source)
I figured I could set a debounce function on the assigning of xxxx in xxxx = $event.target.value
like this
<input
v-bind:value="xxxx"
v-on:input="debounceSearch($event.target.value)"
>
methods:
debounceSearch(val){
if(search_timeout) clearTimeout(search_timeout);
var that=this;
search_timeout = setTimeout(function() {
that.xxxx = val;
}, 400);
},
If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce
Usage:
<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />
Then in your component:
<script>
export default {
name: 'example',
data () {
return {
delay: 1000,
term: '',
}
},
watch: {
term () {
// Do something with search term after it debounced
console.log(`Search term changed to ${this.term}`)
}
},
directives: {
debounce
}
}
</script>
Please note that I posted this answer before the accepted answer. It's not
correct. It's just a step forward from the solution in the
question. I have edited the accepted question to show both the author's implementation and the final implementation I had used.
Based on comments and the linked migration document, I've made a few changes to the code:
In template:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
In script:
watch: {
searchInput: function () {
this.debounceInput();
}
},
And the method that sets the filter key stays the same:
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
This looks like there is one less call (just the v-model, and not the v-on:input).
In case you need to apply a dynamic delay with the lodash's debounce function:
props: {
delay: String
},
data: () => ({
search: null
}),
created () {
this.valueChanged = debounce(function (event) {
// Here you have access to `this`
this.makeAPIrequest(event.target.value)
}.bind(this), this.delay)
},
methods: {
makeAPIrequest (newVal) {
// ...
}
}
And the template:
<template>
//...
<input type="text" v-model="search" #input="valueChanged" />
//...
</template>
NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props
Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this.
https://www.npmjs.com/package/vue-lazy-input
It applies to #input and v-model, supports custom components and DOM elements, debounce and throttle.
Vue.use(VueLazyInput)
new Vue({
el: '#app',
data() {
return {
val: 42
}
},
methods:{
onLazyInput(e){
console.log(e.target.value)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/lodash/lodash.min.js"></script><!-- dependency -->
<script src="https://unpkg.com/vue-lazy-input#latest"></script>
<div id="app">
<input type="range" v-model="val" #input="onLazyInput" v-lazy-input /> {{val}}
</div>
To create debounced methods you can use computeds, that way they won't be shared across multiple instances of your component:
<template>
<input #input="handleInputDebounced">
<template>
<script>
import debounce from 'lodash.debouce';
export default {
props: {
timeout: {
type: Number,
default: 200,
},
},
methods: {
handleInput(event) {
// input handling logic
},
},
computed: {
handleInputDebounced() {
return debounce(this.handleInput, this.timeout);
},
},
}
</script>
You can make it work with uncontrolled v-model as well:
<template>
<input v-model="debouncedModel">
<template>
<script>
import debounce from 'lodash.debouce';
export default {
props: {
value: String,
timeout: {
type: Number,
default: 200,
},
},
methods: {
updateValue(value) {
this.$emit('input', value);
},
},
computed: {
updateValueDebounced() {
return debounce(this.updateValue, this.timeout);
},
debouncedModel: {
get() { return this.value; },
set(value) { this.updateValueDebounced(value); }
},
},
}
</script>
Here is a vue3 way
...
<input v-model="searchInput">
...
setup(){
const searchInput = ref(null)
const timeoutID = ref(null)
watch(searchInput, (new, old) => {
clearTimeout(timeoutID.value)
timeoutID.value = setTimeout(() => {
//Call function for searching
}, 500) //millisecons before it is run
})
return {...}
}
If you are using Vue you can also use v.model.lazy instead of debounce but remember v.model.lazy will not always work as Vue limits it for custom components.
For custom components you should use :value along with #change.native
<b-input :value="data" #change.native="data = $event.target.value" ></b-input>
1 Short version using arrow function, with default delay value
file: debounce.js in ex: ( import debounce from '../../utils/debounce' )
export default function (callback, delay=300) {
let timeout = null
return (...args) => {
clearTimeout(timeout)
const context = this
timeout = setTimeout(() => callback.apply(context, args), delay)
}
}
2 Mixin option
file: debounceMixin.js
export default {
methods: {
debounce(func, delay=300) {
let debounceTimer;
return function() {
// console.log("debouncing call..");
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
// console.log("..done");
};
}
}
};
Use in vueComponent:
<script>
import debounceMixin from "../mixins/debounceMixin";
export default {
mixins: [debounceMixin],
data() {
return {
isUserIdValid: false,
};
},
mounted() {
this.isUserIdValid = this.debounce(this.checkUserIdValid, 1000);
},
methods: {
isUserIdValid(id){
// logic
}
}
</script>
another option, example
Vue search input debounce
Here's an example Vue 2 component that demonstrates how to use debounce.
<template>
<div>
<v-btn #click="properDebounceMyMethod">Proper debounce</v-btn>
<v-btn #click="notWorkingDebounceMyMethod">!debounce</v-btn>
<v-btn #click="myMethod">normal call</v-btn>
</div>
</template>
<script lang="ts" >
import { defineComponent } from '#vue/composition-api';
import { debounce } from 'lodash';
export default defineComponent({
name: 'DebounceExample',
created() {
// debounce instance method dynamically on created hook
this.properDebounceMyMethod = debounce(this.properDebounceMyMethod, 500);
},
methods: {
properDebounceMyMethod(){
this.myMethod();
},
notWorkingDebounceMyMethod() {
debounce(this.myMethod, 500);
},
myMethod() {
console.log('hi from my method');
},
}
});
</script>
If you could move the execution of the debounce function into some class method you could use a decorator from the utils-decorators lib (npm install --save utils-decorators):
import {debounce} from 'utils-decorators';
class SomeService {
#debounce(500)
getData(params) {
}
}
I was able to use debounce with very little implementation.
I am using Vue 2.6.14 with boostrap-vue:
Add this pkg to your package.json: https://www.npmjs.com/package/debounce
Add this to main.js:
import { debounce } from "debounce";
Vue.use(debounce);
In my component I have this input:
<b-form-input
debounce="600"
#update="search()"
trim
id="username"
v-model="form.userName"
type="text"
placeholder="Enter username"
required
>
</b-form-input>
All it does is call the search() method and the search method uses the form.userName for perform the search.
<template>
<input type="text" v-model="search" #input="debouncedSearch" />
</template>
<script>
import _ from 'lodash';
export default {
data() {
return {
search: '',
};
},
methods: {
search() {
// Perform the search here
console.log(this.search);
},
},
created() {
this.debouncedSearch = _.debounce(this.search, 1000);
},
};
</script>
public debChannel = debounce((key) => this.remoteMethodChannelName(key), 200)
vue-property-decorator

Variable not updated after vuex mutation

I am creating a settings page, where I fetch some data from the API and I am using Vuex to handle mutations.
I can see that the Vuex completes properly, but value for my dailyCount variable doesn't update in frontend.
This is my Settings component:
<template>
<div>
<div class="row col">
<h1>Settings</h1>
</div>
<div class="row col">
<div class="well">
<form class="form-inline">
<input type="number" v-model="dailyCount" />
{{ dailyCount }}
</form>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'settings',
data () {
return {
dailyCount: 500
};
},
created () {
this.$store.dispatch('settings/fetchSetting');
},
computed: {
isLoading() {
return this.$store.getters['user/isLoading'];
},
hasError() {
return this.$store.getters['user/hasError'];
},
error() {
return this.$store.getters['user/error'];
},
},
}
</script>
I do mutations here:
import SettingsAPI from '../api/settings';
export default {
namespaced: true,
state: {
isLoading: false,
error: null,
settings: null,
},
getters: {
isLoading (state) {
return state.isLoading;
},
hasError (state) {
return state.error !== null;
},
error (state) {
return state.error;
},
user (state) {
return state.user;
},
},
mutations: {
['FETCHING_SETTINGS'](state) {
state.isLoading = true;
state.error = null;
state.settings = null;
},
['FETCHING_SETTINGS_SUCCESS'](state, settings) {
state.isLoading = false;
state.error = null;
state.settings = settings;
},
['FETCHING_SETTINGS_ERROR'](state, error) {
state.isLoading = false;
state.error = error;
state.settings = null;
},
},
actions: {
fetchSetting ({commit}) {
commit('FETCHING_SETTINGS');
return SettingsAPI.get()
.then(res => {commit('FETCHING_SETTINGS_SUCCESS', res.data);})
.catch(err => commit('FETCHING_SETTINGS_ERROR', err));
},
},
}
And call to a server is done here (api/settings.js - it is imported in mutation file):
import axios from 'axios';
export default {
get() {
return axios.get('/user');
},
}
Can you see what am I doing wrong? I am trying to debug it using Vuejs debug toolbar, but all seems to work fine.
You need to get store state from vuex and inject to Vue component, either by this.$store.state or this.$store.getters.
For example:
<script>
export default {
name: 'settings',
data () {
return {
dailyCount: 500
};
},
created () {
this.$store.dispatch('settings/fetchSetting');
},
computed: {
isLoading() {
return this.$store.getters['user/isLoading'];
},
hasError() {
return this.$store.getters['user/hasError'];
},
error() {
return this.$store.getters['user/error'];
},
settings() {
return this.$store.state.settings
}
},
watch: {
settings () {
this.dailyCount = this.settings.dailyCount
}
}
}
</script>

VueJS set custom component default value from props

Hi guys I tried to create a VueJS custom component to wrap Vue Autonumeric component.
https://github.com/autoNumeric/vue-autoNumeric
In Vue Autonumeric page it specifically mention the caveat
Caveats Please note that directly setting a :value='42' on the
component will break it (really!). Do NOT do that:
So in my custom component MoneyComponent.vue, I create a v-model
This is the full code
<template>
<div>
<vue-autonumeric
v-model="amount"
></vue-autonumeric>
</div>
</template>
<script>
import VueAutonumeric from 'vue-autonumeric/src/components/VueAutonumeric.vue';
export default {
components: {
VueAutonumeric,
},
props: {
value: {},
},
data() {
return {
amount: this.value,
}
},
methods: {
},
watch: {
amount (value) {
this.$emit('input', value);
}
},
}
</script>
Usage example
<template>
<v-money
v-model="price"
></v-money>
</template>
<script>
export default {
data() {
return {
price: 45,
}
},
methods: {
}
}
<script>
This works on on initial value from parent. However if I change the price property to 55 for example, the amount property in MoneyComponent is not changing.
What is the problem here the amount property is not reactive on second changes? How do I fix it?
Thanks
Because you're using v-model, you need to emit input event to make data changed in the parent
watch: {
amount: function (newVal) {
this.$emit('input', newVal)
},
value: function (newVal, oldVal) {
if (newVal !== oldVal) {
this.amount = newVal
}
}
}
then your component
<template>
<div>
<vue-autonumeric
v-model="amount"
></vue-autonumeric>
</div>
</template>
<script>
import VueAutonumeric from 'vue-autonumeric/src/components/VueAutonumeric.vue';
export default {
components: {
VueAutonumeric,
},
props: {
value: {},
},
data() {
return {
amount: this.value,
}
},
watch: {
amount: function (newVal) {
this.$emit('input', newVal)
},
value: function (newVal, oldVal) {
if (newVal !== oldVal) {
this.amount = newVal
}
}
}
}
</script>

How to implement debounce in Vue2?

I have a simple input box in a Vue template and I would like to use debounce more or less like this:
<input type="text" v-model="filterKey" debounce="500">
However the debounce property has been deprecated in Vue 2. The recommendation only says: "use v-on:input + 3rd party debounce function".
How do you correctly implement it?
I've tried to implement it using lodash, v-on:input and v-model, but I am wondering if it is possible to do without the extra variable.
In template:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
In script:
data: function () {
return {
searchInput: '',
filterKey: ''
}
},
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
The filterkey is then used later in computed props.
I am using debounce NPM package and implemented like this:
<input #input="debounceInput">
methods: {
debounceInput: debounce(function (e) {
this.$store.dispatch('updateInput', e.target.value)
}, config.debouncers.default)
}
Using lodash and the example in the question, the implementation looks like this:
<input v-on:input="debounceInput">
methods: {
debounceInput: _.debounce(function (e) {
this.filterKey = e.target.value;
}, 500)
}
Option 1: Re-usable, no deps
- Recommended if needed more than once in your project
/helpers.js
export 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)
}
}
Typescript?
export function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): T {
let timeoutID: number | null = null;
return function (this: any, ...args: any[]) {
clearTimeout(timeoutID);
timeoutID = setTimeout(() => {
fn.apply(this, args);
}, delay);
} as T;
}
Or if using a d.ts:
declare function debounce(fn: (...args: any[]) => void, delay: number): (...args: any[]) => void;
/Component.vue
<script>
import {debounce} from './helpers'
export default {
data () {
return {
input: '',
debouncedInput: ''
}
},
watch: {
input: debounce(function (newVal) {
this.debouncedInput = newVal
}, 500)
}
}
</script>
Codepen
Option 2: In-component, also no deps
- Recommended if using once or in small project
/Component.vue
<template>
<input type="text" v-model="input" />
</template>
<script>
export default {
data: {
timeout: null,
debouncedInput: ''
},
computed: {
input: {
get() {
return this.debouncedInput
},
set(val) {
if (this.timeout) clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.debouncedInput = val
}, 300)
}
}
}
}
</script>
Codepen
Assigning debounce in methods can be trouble. So instead of this:
// Bad
methods: {
foo: _.debounce(function(){}, 1000)
}
You may try:
// Good
created () {
this.foo = _.debounce(function(){}, 1000);
}
It becomes an issue if you have multiple instances of a component - similar to the way data should be a function that returns an object. Each instance needs its own debounce function if they are supposed to act independently.
Here's an example of the problem:
Vue.component('counter', {
template: '<div>{{ i }}</div>',
data: function(){
return { i: 0 };
},
methods: {
// DON'T DO THIS
increment: _.debounce(function(){
this.i += 1;
}, 1000)
}
});
new Vue({
el: '#app',
mounted () {
this.$refs.counter1.increment();
this.$refs.counter2.increment();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
<div id="app">
<div>Both should change from 0 to 1:</div>
<counter ref="counter1"></counter>
<counter ref="counter2"></counter>
</div>
Very simple without lodash
handleScroll: function() {
if (this.timeout)
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
// your action
}, 200); // delay
}
I had the same problem and here is a solution that works without plugins.
Since <input v-model="xxxx"> is exactly the same as
<input
v-bind:value="xxxx"
v-on:input="xxxx = $event.target.value"
>
(source)
I figured I could set a debounce function on the assigning of xxxx in xxxx = $event.target.value
like this
<input
v-bind:value="xxxx"
v-on:input="debounceSearch($event.target.value)"
>
methods:
debounceSearch(val){
if(search_timeout) clearTimeout(search_timeout);
var that=this;
search_timeout = setTimeout(function() {
that.xxxx = val;
}, 400);
},
If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce
Usage:
<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />
Then in your component:
<script>
export default {
name: 'example',
data () {
return {
delay: 1000,
term: '',
}
},
watch: {
term () {
// Do something with search term after it debounced
console.log(`Search term changed to ${this.term}`)
}
},
directives: {
debounce
}
}
</script>
Please note that I posted this answer before the accepted answer. It's not
correct. It's just a step forward from the solution in the
question. I have edited the accepted question to show both the author's implementation and the final implementation I had used.
Based on comments and the linked migration document, I've made a few changes to the code:
In template:
<input type="text" v-on:input="debounceInput" v-model="searchInput">
In script:
watch: {
searchInput: function () {
this.debounceInput();
}
},
And the method that sets the filter key stays the same:
methods: {
debounceInput: _.debounce(function () {
this.filterKey = this.searchInput;
}, 500)
}
This looks like there is one less call (just the v-model, and not the v-on:input).
In case you need to apply a dynamic delay with the lodash's debounce function:
props: {
delay: String
},
data: () => ({
search: null
}),
created () {
this.valueChanged = debounce(function (event) {
// Here you have access to `this`
this.makeAPIrequest(event.target.value)
}.bind(this), this.delay)
},
methods: {
makeAPIrequest (newVal) {
// ...
}
}
And the template:
<template>
//...
<input type="text" v-model="search" #input="valueChanged" />
//...
</template>
NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props
Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this.
https://www.npmjs.com/package/vue-lazy-input
It applies to #input and v-model, supports custom components and DOM elements, debounce and throttle.
Vue.use(VueLazyInput)
new Vue({
el: '#app',
data() {
return {
val: 42
}
},
methods:{
onLazyInput(e){
console.log(e.target.value)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/lodash/lodash.min.js"></script><!-- dependency -->
<script src="https://unpkg.com/vue-lazy-input#latest"></script>
<div id="app">
<input type="range" v-model="val" #input="onLazyInput" v-lazy-input /> {{val}}
</div>
To create debounced methods you can use computeds, that way they won't be shared across multiple instances of your component:
<template>
<input #input="handleInputDebounced">
<template>
<script>
import debounce from 'lodash.debouce';
export default {
props: {
timeout: {
type: Number,
default: 200,
},
},
methods: {
handleInput(event) {
// input handling logic
},
},
computed: {
handleInputDebounced() {
return debounce(this.handleInput, this.timeout);
},
},
}
</script>
You can make it work with uncontrolled v-model as well:
<template>
<input v-model="debouncedModel">
<template>
<script>
import debounce from 'lodash.debouce';
export default {
props: {
value: String,
timeout: {
type: Number,
default: 200,
},
},
methods: {
updateValue(value) {
this.$emit('input', value);
},
},
computed: {
updateValueDebounced() {
return debounce(this.updateValue, this.timeout);
},
debouncedModel: {
get() { return this.value; },
set(value) { this.updateValueDebounced(value); }
},
},
}
</script>
Here is a vue3 way
...
<input v-model="searchInput">
...
setup(){
const searchInput = ref(null)
const timeoutID = ref(null)
watch(searchInput, (new, old) => {
clearTimeout(timeoutID.value)
timeoutID.value = setTimeout(() => {
//Call function for searching
}, 500) //millisecons before it is run
})
return {...}
}
If you are using Vue you can also use v.model.lazy instead of debounce but remember v.model.lazy will not always work as Vue limits it for custom components.
For custom components you should use :value along with #change.native
<b-input :value="data" #change.native="data = $event.target.value" ></b-input>
1 Short version using arrow function, with default delay value
file: debounce.js in ex: ( import debounce from '../../utils/debounce' )
export default function (callback, delay=300) {
let timeout = null
return (...args) => {
clearTimeout(timeout)
const context = this
timeout = setTimeout(() => callback.apply(context, args), delay)
}
}
2 Mixin option
file: debounceMixin.js
export default {
methods: {
debounce(func, delay=300) {
let debounceTimer;
return function() {
// console.log("debouncing call..");
const context = this;
const args = arguments;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
// console.log("..done");
};
}
}
};
Use in vueComponent:
<script>
import debounceMixin from "../mixins/debounceMixin";
export default {
mixins: [debounceMixin],
data() {
return {
isUserIdValid: false,
};
},
mounted() {
this.isUserIdValid = this.debounce(this.checkUserIdValid, 1000);
},
methods: {
isUserIdValid(id){
// logic
}
}
</script>
another option, example
Vue search input debounce
Here's an example Vue 2 component that demonstrates how to use debounce.
<template>
<div>
<v-btn #click="properDebounceMyMethod">Proper debounce</v-btn>
<v-btn #click="notWorkingDebounceMyMethod">!debounce</v-btn>
<v-btn #click="myMethod">normal call</v-btn>
</div>
</template>
<script lang="ts" >
import { defineComponent } from '#vue/composition-api';
import { debounce } from 'lodash';
export default defineComponent({
name: 'DebounceExample',
created() {
// debounce instance method dynamically on created hook
this.properDebounceMyMethod = debounce(this.properDebounceMyMethod, 500);
},
methods: {
properDebounceMyMethod(){
this.myMethod();
},
notWorkingDebounceMyMethod() {
debounce(this.myMethod, 500);
},
myMethod() {
console.log('hi from my method');
},
}
});
</script>
If you could move the execution of the debounce function into some class method you could use a decorator from the utils-decorators lib (npm install --save utils-decorators):
import {debounce} from 'utils-decorators';
class SomeService {
#debounce(500)
getData(params) {
}
}
I was able to use debounce with very little implementation.
I am using Vue 2.6.14 with boostrap-vue:
Add this pkg to your package.json: https://www.npmjs.com/package/debounce
Add this to main.js:
import { debounce } from "debounce";
Vue.use(debounce);
In my component I have this input:
<b-form-input
debounce="600"
#update="search()"
trim
id="username"
v-model="form.userName"
type="text"
placeholder="Enter username"
required
>
</b-form-input>
All it does is call the search() method and the search method uses the form.userName for perform the search.
<template>
<input type="text" v-model="search" #input="debouncedSearch" />
</template>
<script>
import _ from 'lodash';
export default {
data() {
return {
search: '',
};
},
methods: {
search() {
// Perform the search here
console.log(this.search);
},
},
created() {
this.debouncedSearch = _.debounce(this.search, 1000);
},
};
</script>
public debChannel = debounce((key) => this.remoteMethodChannelName(key), 200)
vue-property-decorator