Following an answer to my question on debouncing I am wondering if vue.js and lodash/underscore are compatible for this functionality. The code in the answer
var app = new Vue({
el: '#root',
data: {
message: ''
},
methods: {
len: _.debounce(
function() {
return this.message.length
},
150 // 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">Length: <span>{{ len() }}</span>
</div>
indeed holds on the execution of my function when there is continuous input, but when it is finally executed after some inactivity, the input for function() seems to be wrong.
A practical example after starting the code above:
quick sequence of characters, then no activity:
One extra character (b) added, and no activity -- the length is updated (but wrongly, see below)
Erase all the characters with Backspace in a quick sequence:
Add one character:
It looks like the function is ran on the last but one value of message.
Could it be that _.debounce handles the vue.js data before it is actually updated with the <input> value?
Notes:
tested with both lodash and underscore, with the same results (for both debounceand throttle functions).
I also tested it on JSFiddle in case there would be some interference with the SO snippet
Here's an improved version of #saurabh's version.
var app = new Vue({
el: '#root',
data: {
message: '',
messageLen: 0
},
methods: {
updateLen: _.debounce(
function() {
this.messageLen = this.message.length
}, 300)
}
})
<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="updateLen">Length: <span>{{ messageLen }}</span>
</div>
Why this is happening is because Vue invokes methods only when vue variables used in the methods changes, if there are no changes in the vue varaibles, it will not trigger those methods.
In this case as well, once we stop typing, it will continue to show last called method's output and will only show again once you enter the input again.
One alternate approach if you dont want to call an function on all inputs, you can call a mehtod on blur event, so method will be invoked only when focus goes out of input field, like following:
var app = new Vue({
el: '#root',
data: {
message: '',
messageLen: 0
},
methods: {
updatateLen:
function() {
this.messageLen = this.message.length
}
}
})
<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:blur="updatateLen">Length: <span>{{ messageLen }}</span>
</div>
Related
I have an input field and I want the contents to read 'ab****gh' and be able to toggle the contents with a click to read 'abcdefgh'. Basically a reveal and not reveal. I'm having trouble making the value reactive when I change it. Below is some partial code that I've been working with.
Basically i'm trying to swap the content of the input with the encrypted value
Can anyone see where I'm going wrong?
regex_hide_characters: /(?<!^).(?!$)/g,
inputValue: this.value,
encryptedInputValue: this.value.replace(this.regex_hide_characters, '*'),
hidePrivateContent() {
this.reveal = !this.reveal;
if (!this.reveal) {
this.$refs.input.value = this.encryptedInputValue;
}
},
Here is a very basic sample of how you'd achieve something like this:
new Vue({
el: '#app',
computed: {
hiddenPass() {
if (this.isPass) return this.pass.slice(0, 2) + '*******';
return this.pass;
}
},
data() {
return {
isPass: true,
pass: 'abc124defg'
}
},
methods: {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" v-cloak>
<div>{{hiddenPass}}</div>
<button #click="isPass=!isPass">toggle view</button>
</div>
In the snippet, I'm taking advantage of computed properties in order to determine, based on data on the instance, how to show the "protected" pass.
I hope this helps!
I'm using vue-select in my app and am trying to prevent an event handler from firing when the default values are first loaded into the vue-select input.
The component looks like this:
<v-select
multiple
v-model="product.recommended_accessories"
label="name"
:options="accessoryOptions"
#input="saveProduct"
#search="onAccessorySearch">
<template slot="option" slot-scope="option">
<h4>{{ option.name }}</h4>
<h5>{{ option.sku }}</h5>
</template>
</v-select>
As you can see, I want to save the product when the user changes the values in this multi-select. It works fine, but with one issue.
The value of the select is tied to the product.recommended_accessories data. Elsewhere in the app, a product is loaded from the server, which includes a recommended_accessories attribute. Loading the product then triggers saveProduct to be called since vue-select set the preselected options for the input, which apparently triggers the #input event.
Is there anyway around this? Maybe I have made some sort of design error here. Or maybe there is a hook I should be using to bind the event handler, or to set some sort of flag indicating that the product is in the process of being loaded and saving the product shouldn't occur.
I'm just trying to avoid saving the product immediately after it's loaded for no reason.
For now I am just tracking an accessoryEventCount variable that gets initialized to 0 whenever a product is loaded. Then I make sure accessoryEventCount > 0 before calling saveProduct on an v-select input event.
It works, but I am still wondering if there is a more elegant solution.
UPDATE
Looks like Vue.nextTick is what I was looking for. Before setting the value of product in code, I set a flag this.isSettingProduct = true. Then I set the product, and call Vue.nextTick(() => { this.isSettingProduct = false });.
Now I can avoid saving the product if this.isSettingProduct == true. Using Vue.nextTick ensures that the flag isn't set back to false until after the asynchronous data update completes.
It looks you should bind prop=onChange, though #input still seems working (check v-select github: line# 544).
Below is my solution, before loading your product, bind onChange with function () {}, after loaded, bind it with the function you like.
Vue.component('v-select', VueSelect.VueSelect)
app = new Vue({
el: "#app",
data: {
accessoryOptions: [
{'name':'a1', 'sku':'a2'},
{'name':'b1', 'sku':'b2'},
{'name':'c1', 'sku':'c2'}
],
product: {
recommended_accessories: []
},
saveProduct: function (){}
},
methods: {
onAccessorySearch: function () {
console.log('emit input')
},
loadProduct: function () {
this.product.recommended_accessories = ['a1', 'b1'] // simulate get data from the server
setTimeout( () => {
this.saveProduct = (value) => {
console.log('emit input', this.product.recommended_accessories)
}
}, 400)
}
}
})
#app {
width: 400px;
}
<script src="https://unpkg.com/vue#latest"></script>
<script src="https://unpkg.com/vue-select#latest"></script>
<div id="app">
<button #click="loadProduct()">Click Me!</button>
<v-select
multiple
v-model="product.recommended_accessories"
label="name"
:options="accessoryOptions"
:on-change="saveProduct"
#search="onAccessorySearch">
<template slot="option" slot-scope="option">
<span>{{ option.name }}</span>
<span>{{ option.sku }}</span>
</template>
</v-select>
</div>
I have worked with VueJS for a while, and it is great. I have been able to integrate it with jQueryUI (for an old looking website) and I created a datepicker component, and a datetime picker component as well, both working correctly.
Now I am trying to create a simple phone number component, which simply provides an input with a mask that helps with the phone number format. The plugin for jquery that provides the masking, works correctly on it's own, but if I try to mask an input inside my component, it does not work.
Here is the example code in jsfiddle:
Simple Masked Phone input component for vuejs 2.4.0 - jsfiddle
Javascript:
Vue.component('phone', {
template: '#phone',
props: {
value : {
type : String,
default: ''
},
mask: {
type : String,
default: '(999) 999-9999'
}
},
data: function() {
return {
internalValue: ''
};
},
created: function() {
this.internalValue = $.trim(this.value);
},
mounted: function() {
$(this.$el).find('.phone:eq(0)').mask('(999) 999-9999');
},
methods: {
updateValue: function (value) {
this.$emit('input', value);
}
}
});
var vueapp = new Vue({
el: '#content',
data: {
myphone: ''
}
});
$('.phonex').mask('(999) 999-9999');
HTML:
<div id="content">
<script type="text/x-template" id="phone">
<input type="text" class="phone" v-model="internalValue" v-on:input="updateValue($event.target.value)" />
</script>
<label>Vue Phone</label>
<phone v-model="myphone"></phone>
<br />
{{ myphone }}
<br />
<label>Simple Phone</label>
<input type="text" class="phonex" />
</div>
This is what I see:
Dependencies:
jquery-2.2.4.min.js
jquery.maskedinput.min.js (1.4.1)
vue.js (2.4.0)
Is there anything I am doing wrong here? Thanks.
You don't need the .find('.phone:eq(0)') in your jquery, removing it seems to fix the masking (as shown here), though this does seem to mess with Vue's data binding.
After doing a bit more digging it looks like this is a known issue.
And is addressed here:
Vue is a jealous library in the sense that you must let it completely
own the patch of DOM that you give it (defined by what you pass to
el). If jQuery makes a change to an element that Vue is managing, say,
adds a class to something, Vue won’t be aware of the change and is
going to go right ahead and overwrite it in the next update cycle.
The way to fix this is to add the event handler when you call .mask on the element.
So for example:
mounted: function() {
var self = this;
$(this.$el).mask('(999) 999-9999').on('keydown change',function(){
self.$emit('input', $(this).val());
})
},
Here is the fiddle with the fix: https://jsfiddle.net/vo9orLx2/
I've got two problems here. The first is that I can't get the star rendered properly. I can do it if I change the value in the data() function but if I want to do it in a function callback way, it doesn't work (see comments below). What's going wrong here? Does it have something to do with Vue's lifecycle?
The second one is that I want to submit the star-rate and the content of the textarea and when I refresh the page, the content should be rendered on the page and replace the <textarea></textarea> what can I do?
I want to make a JSFiddle here but I don't know how to make it in Vue's single-file component, really appreciate your help.
<div class="order-comment">
<ul class="list-wrap">
<li>
<span class="comment-label">rateA</span>
<star-rating :data="dimensionA"></star-rating>
</li>
</ul>
<div>
<h4 class="title">comment</h4>
<textarea class="content" v-model="content">
</textarea>
</div>
<mt-button type="primary" class="mt-button">submit</mt-button>
</div>
</template>
<script>
import starRating from 'components/starRating'
import dataService from 'services/dataService'
export default {
data () {
return {
dimensionA: '' //if I changed the value here the star rendered just fine.
}
},
components: {
starRating
},
methods: {
getComment (id) {
return dataService.getOrderCommentList(id).then(data => {
this.dimensionA = 1
})
}
},
created () {
this.getComment(1) // not working
}
}
</script>
What it seems is scope of this is not correct in your getComment method, you need changes like following:
methods: {
getComment (id) {
var self = this;
dataService.getOrderCommentList(id).then(data => {
self.dimensionA = 1
})
}
},
As you want to replace the <textarea> and render the content if present, you can use v-if for this, if content if available- show content else show <textarea>
<div>
<h4 class="title">comment</h4>
<span v-if="content> {{content}} </span>
<textarea v-else class="content" v-model="content">
</textarea>
</div>
See working fiddle here.
one more problem I have observed in your code is you are using dynamic props, but you have assigned the prop initially to the data variable value in star-rating component, but you are not checking future changes in the prop. One way to solve this, assuming you have some other usage of value variable is putting following watch:
watch:{
data: function(newVal){
this.value = newVal
}
}
see updated fiddle.
I have input which I use to filter my array of objects in Vue. I'm using Salvattore to build a grid of my filtered elements, but it doesn't work too well. I think I have to call rescanMediaQueries(); function after my v-model changes but can't figure how.
Here is my Vue instance:
var articlesVM = new Vue({
el: '#search',
data: {
articles: [],
searchInput: null
},
ready: function() {
this.$http.get('posts').then(function (response) {
this.articles = response.body;
});
}
});
And here is how I have built my search
<div class="container" id="search">
<div class="input-field col s6 m4">
<input v-model="searchInput" class="center-align" id="searchInput" type="text" >
<label class="center-align" for="searchInput"> search... </label>
</div>
<div id="search-grid" v-show="searchInput" data-columns>
<article v-for="article in articles | filterBy searchInput">
<div class="card">
<div class="card-image" v-if="article.media" v-html="article.media"></div>
<div class="card-content">
<h2 class="card-title center-align">
<a v-bind:href="article.link">{{ article.title }}</a>
</h2>
<div class="card-excerpt" v-html="article.excerpt"></div>
</div>
<div class="card-action">
<a v-bind:href="article.link"><?php _e('Read More', 'sage'); ?></a>
</div>
</div>
</article>
</div>
I did get the grid system working by adding watch option to my Vue, but every time I wrote something to my input and then erase it my filterBy method wouldn't work at all. It didn't populate any data even if I tried to retype the same keyword as earlier. Here is the watch option I used:
watch: {
searchInput: function (){
salvattore.rescanMediaQueries();
}
}
I think your problem is with the scoping of this in your success handler for http. Your articles object in Vue component is not getting any values from your http.get(..) success handler.
Inside your ready function, your http success handler should be as follows:
this.$http.get('posts').then(response => {
this.articles = response.body; // 'this' belongs to outside scope
});`
Alternatively you can also do:
var self = this; // self points to 'this' of Vue component
this.$http.get('posts').then(response => {
self.articles = response.body; // 'self' points to 'this' of outside scope
});`
Another similar issue: https://stackoverflow.com/a/40090728/654825
One more thing - it is preferable to define data as a function, as follows:
var articlesVM = new Vue({
el: '#search',
data: function() {
return {
articles: [],
searchInput: null
}
},
...
}
This ensures that your articles object is unique to this instance of the component (when you use the same component at multiple places within your app).
Edited after comment #1
The following code seems to work alright, the watch function works flawlessly:
var vm = new Vue({
el: '#search',
template: `<input v-model="searchInput" class="center-align" id="searchInput" type="text" >`,
data: {
searchInput: ""
},
watch: {
searchInput: function() {
console.log("searchInput changed to " + this.searchInput);
}
}
})
The input in template is an exact copy of your version - I have even set the id along with v-model, though I do not see the reason to set an id
Vue.js version: 2.0.3
I am unable to see any further, based on details in the question. Can you check if your code matches with the one above and see if you can get the console debugging messages?
Edited after comment #4, #5
Here is another thought which you need to verify:
Role of vue.js: Render the DOM
Role of salvattore plugin: Make the DOM layouts using CSS only
Assuming the above is true for salvattore plugin, and hopefully it does not mess with vue.js observers / getters / setters, then you can do the following: provide a time delay of about 50 ms so that vue.js completes the rendering, and then call the salvattore plugin to perform the layouts.
So your watch function needs to be as follows:
watch: {
searchInput: function (){
setTimeout(function(){
salvattore.rescanMediaQueries();
}, 50);
}
}
Alternatively you may also use Vue.nexttick() as follows:
Vue.nextTick(function () {
// DOM updated
})
The nextTick is documented here: https://vuejs.org/api/#Vue-nextTick
I do not know if you may need to provide a little bit of extra time for salvattore plugin to start the layouts, but one of the above should work out.
Let me know if it works!