Dropdown and Vuetify - vue.js

I have installed fresh Vue.js and Vuetify.
For some reason, my tag, which is used for dropdown menu with autosuggest is not visible anymore. jQuery lib and select2 package are installed.
or are visible and working.
Is there a conflict with Vuetify? Maybe I forgot to install some package?
Even after I unhide my in inspector (by changing bg-color property) it is visible, but still not working.
How could I check, if the problem is with Vuetify?
How to check, whether it's a problem of some packages not installed?
<template>
<div class="information">
<div> <select style="display:block" id="location" data-placeholder="Von:" data-width="30%"></select>
</div>
</div>
</template>
<script>
import $ from 'jquery'
export default {
name: "HereAddressLookup",
data() {
return {
};
},
mounted() {
var options = {
minimumInputLength: 1,
ajax: {
url: 'https://autocomplete.geocoder.ls.hereapi.com/6.2/suggest.json',
delay: 250,
dataType: 'json',
data: function (params) {
return {
query: params.term,
apiKey: 'v35d7iIj8nuBconhXjWobmSTzQbz8tL99jhnDGTR-ds',
beginHighlight: '<b>',
endHighlight: '</b>',
country: 'DEU'
};
},
processResults: function (data) {
return {
results: $.map(data.suggestions, function (obj) {
return { id: obj.locationId, text: obj.label.split(', ').reverse().join(', ') };
})
};
}
},
escapeMarkup: function (markup) { return markup; }
};
$('#location').select2(options).on('select2:select', function (e) {
$.getJSON('https://geocoder.ls.hereapi.com/6.2/geocode.json', {
apiKey: 'v35d7iIj8nuBconhXjWobmSTzQbz8tL99jhnDGTR-ds',
locationId: e.params.data.id
}).done(function (data) {
var locn = data.Response.View[0].Result[0].Location;
var opts = {
apiKey: 'v35d7iIj8nuBconhXjWobmSTzQbz8tL99jhnDGTR-ds',
variant: 'normal.day'
};
});
});
},
}
</script>
How it should look:

Related

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

Vue. Autosave input value with localstorage

I have a component with a form for which I need to implement data autosave when entering content. How to apply an example for v-model = "titleName" to v-model = "article.title[currentLanguage]"?
P.S. currentLanguage is taken from store
<div id="app">
Title is <input type="text" name="titleName" id="titleName" v-model="titleName">
Title is <input type="text" name="article" id="article"
v-model="article.title.en">
</div>
<script>
var app = new Vue({
el:'#app',
data: {
titleName: '',
article: {
title: {
en: null,
ru: null
}
}
},
computed: {
availableLanguages() {
return this.$store.state.languages;
}
},
created() {
this.setDefaults();
},
mounted () {
const SAVED = localStorage.getItem('content')
if (SAVED) {
this.titleName = SAVED
}
},
watch: {
titleName(newTitleName) {
localStorage.content = newTitleName;
}
}
</script>
https://codepen.io/pershay/pen/EJQGGO
Just use localStorage.setItem('titleName', newTitleName) and localStorage.getItem('titleName')
You don't need to load on mounted. Place it in the data function itself. I think this is the better way:
var app = new Vue({
data:() => ({
titleName: localStorage.getItem('titleName'),
article: JSON.parse(localStorage.getItem('article'))
}),
watch: {
titleName(newTitleName) {
localStorage.setItem('titleName', newTitleName)
},
article(newArticle) {
handler: function(newArticle) {
localStorage.setItem('article', JSON.stringify(newArticle))
},
deep: true
},
}
The example above also includes a deep object watch.

Can’t select options from options list

I have a dropdown list called login. The list is shown when I load the page, but I can’t select an option from the list. Why is that?
I have searched the internet but didn’t find a solution.
This is the code from the component:
<template>
<div>
<label for="login" class="control-label">Logins anlegen für</label>
<select2 class="select2_tag form-control" name="login"
multiple="multiple" :options="login">
</select2>
</div>
</template>
<script>
import JQuery from 'jquery'
let $ = JQuery
import Select2 from '#/components/Select2.vue'
export default {
name: 'Login',
data: function () {
return {
login: [],
loginUebertrag: ''
}
},
components: {
Select2
},
methods: {
lade_login: function () {
let vm = this;
$.getJSON("/api/get_login.php", function (result) {
vm.login = result;
console.log("zeile 41: ", vm.login);
});
},
},
mounted()
{
this.lade_login();
}
}
</script>
And this is the code from the imported component (called select2):
<template>
<select class="form-control" >
<slot></slot>
</select>
</template>
<script>
import JQuery from 'jquery'
let $ = JQuery
export default {
name: 'select2',
props: ['options', 'value'],
mounted: function () {
var vm = this
$(this.$el)
// init select2
.select2({
data: this.options,
tags:true
})
//.val(this.value)
//.trigger('change')
// emit event on change.
.on('change', function () {
vm.$emit('input', this.value)
});
console.log( $(this.$el))
},
watch: {
value: function (value) {
// update value
//console.log(value)
$(this.$el)
.val(value)
.trigger('change')
},
options: function (options) {
// update options
$(this.$el).empty().select2({data: options,tags: true})
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
}
</script>
Any help is appreciated!

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

VueJS: Setting data initially based on http response

So I have a template .vue file:
<template>
<div id="app">
<textarea v-model="input" :value="input" #input="update"></textarea>
<div v-html="compiledMarkdown"></div>
</div>
</template>
<script>
var markdown = require('markdown').markdown;
export default {
name: 'app',
data() {
return {
input: '# Some default data'
}
},
mounted: function () {
this.$nextTick(function () {
this.$http.get(window.location.pathname + '/data').then((response) => {
this.input = response.body.markdown;
}) })
},
computed: {
compiledMarkdown: function() {
this.$http.post(window.location.pathname, {
"html": markdown.toHTML(this.input)}).then(function() {
},function() {
});
return markdown.toHTML(this.input);
}
},
methods: {
update: function(e) {
this.input = e.target.value
}
}
}
</script>
In the mounted function I am trying to set input equal to the response of an HTTP request, but when you view this file this.input is still the same as it was initially declared. How can I change this.input inside the compiledMarkdown function to be this.input in the mounted function. What other approaches might I take?
You can not call a async method from a computed property, you can use method or watcher to run asynchronous code, from docs
This is most useful when you want to perform asynchronous or expensive operations in response to changing data.
You have to ran that relevant code when input changes, like following:
var app = new Vue({
el: '#app',
data: {
input: '# Some default data',
markdown : ''
},
methods: {
fetchSchoolData: function (schoolId) {
var url = this.buildApiUrl('/api/school-detail?schoolId=' + schoolId);
this.$http.get(url).then(response => {
this.schoolsListData = response.data;
}).catch(function (error) {
console.log(error);
});
},
},
mounted: function () {
this.$nextTick(function () {
this.$http.get(window.location.pathname + '/data').then((response) => {
this.input = response.body.markdown;
})
})
},
watch: {
// whenever input changes, this function will run
input: function (newInput) {
this.$http.post(window.location.pathname, {
"html": markdown.toHTML(this.input)}).then(function() {
},function() {
this.markdown = markdown.toHTML(this.input);
});
}
},
Have a look at my similar answer here.