Vue.js Input field loses its focus after entry of one character - javascript

I have a view with an input field, which can be multiplicated by a given button. The problem is that after any entry of a char, the focus of the input field is lost. You have to click again to enter another char.
Do someone have a clue what could be the problem?
My model:
'model': [
...,
'filter': [
...,
'something': [
'string'
]
]
]
My code:
<div v-for="(something, index) in model.filter.something" v-bind:key="something">
<input type="text" v-model.trim="model.filter.something[index]"/>
</div>

The problem is that you are using a changing value as key. Vue expects key to indicate a unique identifier for the item. When you change it, it becomes a new item and must be re-rendered.
In the snippet below, I have two loops, both using the same data source. The first is keyed the way you have it set up. The second uses index instead (that may not be what you need, but the point is to use something other than what you're editing; in this example, key isn't needed anyway). The first exhibits the loss-of-focus you describe, the second works as expected.
new Vue({
el: '#app',
data: {
'model': {
'filter': {
'something': [
'string'
]
}
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
<div v-for="(something, index) in model.filter.something" v-bind:key="something">
<input type="text" v-model.trim="model.filter.something[index]" />
{{something}}
</div>
<div v-for="(something, index) in model.filter.something">
<input type="text" v-model.trim="model.filter.something[index]" :key="index" />
{{something}}
</div>
</div>

Related

Vue 3 custom checkbox component with v-model and array of items

Desperately in need of your help guys.
So basically I have a custom checkbox component whit a v-model. I use a v-for loop on the component to display checkboxes with the names from the array. In the parent component I have two columns Available and Selected. The idea is that if I check one of the boxes in the Available column it should appear on the Selected column. The problem is that it displays letter by letter and not the full name.
I am able to achieve the desired result without having a checkbox component, but since I will be needing checkboxes a lot throught my project I want to have a component for it.
Please follow the link for the code:
CodeSandBox
Dont mind the difference in styling.
The problem:
The desired outcome:
There are two problems. The first problem is, that you have your v-model set to v-model="filter.filterCollection", so a checkbox you select will be stored into the array as a string and if you select another checkbox the string gets overwritten. The second problem is, that you call that stored string as an array. That causes, that your string, which is an array of letters, will be rendered for each letter. So 'Number' is like ["N", "u", "m", "b", "e", "r"].
To solve your problem, you need to store every selection with its own reference in your v-model. To cover your needs of correct listing and correct deleting you need to apply the following changes:
Your checkbox loop
<Checkbox
v-for="(item, index) in items"
:key="item.id"
:label="item.name"
:id="index"
:isChecked="isChecked(index)" // this is new
#remove-selected-filter="removeSelectedFilter" // This is new
:modelValue="item.name"
v-model="filter.filterCollection[index]" // Change this
/>
Your v-model
filter: {
filterCollection: {} // Object instead of array
}
Methods in FilterPopUp.vue
methods: {
removeSelectedFilter(index) {
delete this.filter.filterCollection[index];
},
isChecked(index) {
return !!this.filter.filterCollection[index];
}
}
Your Checkbox.vue:
<template>
<label>
<p>{{ label }}</p>
<input
type="checkbox"
:id="id"
:value="modelValue"
:checked="isChecked"
#change="emitUncheck($event.target.checked)"
#input="$emit('update:modelValue', $event.target.value)"
/>
<span class="checkmark"></span>
</label>
</template>
<script>
export default {
name: "Checkbox",
props: {
modelValue: { type: String, default: "" },
isChecked: Boolean,
label: { type: String },
value: { type: Array },
id: { type: Number },
},
methods: {
emitUncheck(event) {
if(!event){
this.$emit('remove-selected-filter', this.id);
}
}
}
};
</script>
This should now display your items properly, delete the items properly and unselect the checkboxes after deleting the items.
StevenSiebert has correctly pointed to your errors.
But his solution is not complete, since the filters will not be removed from the collection when you uncheck one of them.
Here is my complete solution of your checkbox working as expected:
Checkbox.vue
<template>
<label>
<p>{{ label }}</p>
<input
type="checkbox"
:id="id"
v-model="checked"
#change="$emit('change', { id: this.id, checked: this.checked})"
/>
<span class="checkmark"></span>
</label>
</template>
<script>
export default {
name: "Checkbox",
props: {
modelValue: { type: Boolean, default: false },
label: { type: String },
id: { type: Number },
},
emits: ["change"],
data() {
return {
checked: this.modelValue
};
}
};
</script>
FilterPopUp.vue
<template>
...
<Checkbox
v-for="(item, index) in items"
:key="index"
:label="item.name"
:id="index"
#change="onChange"
/>
...
</template>
<script>
...
methods: {
removeSelectedFilter(index) {
this.filter.filterCollection.splice(index, 1);
},
onChange(args) {
const {id, checked} = args;
const item = this.items[id].name;
if (checked) {
if (this.filter.filterCollection.indexOf(item) < 0) {
this.filter.filterCollection.push(item);
}
} else {
this.filter.filterCollection = this.filter.filterCollection.filter( i=> i != item);
}
},
},
...
Here is the working CodeSandbox:
https://codesandbox.io/s/pensive-shadow-ygvzb?file=/src/components/Checkbox.vue
Sure, there are many ways to do it. If somebody has a nicer and shorter way to do it, please post your solution. It will be interesting to look at it.

How to set default value on dynamic input fields in Vue.js?

I have created a dynamic input fields but the problem is that I don't know how to set default values on that dynamic fields for example number "1". Can anyone help me with that? Thanks
Here is my example
new Vue({
el: '#app',
data: {
result: [],
array: [{
id: 1
}, {
id: 2
}, {
id: 3
}]
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div v-for="(item, index) in array" :key="item.id">
<input type="number" :id="item.id" v-model="result[index]">
<br>
</div>
<span>Result: {{ result }}</span>
</div>
As Vue js is reactive you can simply set initial value in result
new Vue({
el: '#app',
data: {
result: ["1","1","1"],
array: [{
id: 1
}, {
id: 2
}, {
id: 3
}]
}
})
According to the official documentation,
v-model will ignore the initial value, checked or selected attributes
found on any form elements. It will always treat the Vue instance data
as the source of truth. You should declare the initial value on the
JavaScript side, inside the data option of your component.
I think it is a design decision of Vue to use the benefit of Vue instance’s reactive system rather than listening to DOM updates when such attributes are updated.
So you can put directly your default values into the result array, here's the updated working jsfiddle.

Array change detection for an array of complex objects in Vue JS 2

Update
Vue JS 3 will properly handle this: https://blog.cloudboost.io/reactivity-in-vue-js-2-vs-vue-js-3-dcdd0728dcdf
Problem:
I have a vue component that looks like this:
sub-comp.vue
<template>
<div>
<input type="text" class="form-control" v-model="textA">
<input type="text" class="form-control" v-model="textB">
<input type="text" class="form-control" v-model="textC">
</div>
</template>
<script>
export default {
props: {
textA: {
type: Number,
required: false
},
textB: {
type: Number,
required: false
},
textC: {
type: Number,
required: false
}
}
}
</script>
I have a parent component that looks like this:
layout-comp.vue
<template>
<div>
<button #click="addItem">Add</button>
<ul>
<li v-for="listItem in listItems"
:key="listItem.id">
<sub-comp
:textA="listItem.item.textA"
:textB="listItem.item.textB"
:textC="listItem.item.textC"
/>
</li>
</ul>
</div>
</template>
import subComp from '../sub-comp.vue'
export default {
components: {
subComp
},
data() {
return {
listItems: []
}
},
methods: {
addItem: function () {
var item = {
textA: 5,
textB: 100,
textC: 200
}
if (!item) {
return
}
this.length += 1;
this.listItems.push({
id: length++,
item: item
});
}
}
</script>
The thing is, anything I do to edit the textboxes, the array doesn't get changed, even though the reactive data shows that it changed. For example, it will always be as
{
textA: 5,
textB: 100,
textC: 200
}
Even if I changed textB: 333, the listItems array still shows textB: 100. This is because of this:
https://v2.vuejs.org/v2/guide/list.html#Caveats
Due to limitations in JavaScript, Vue cannot detect the following changes to an array
Question:
I'm wondering how do I update the array? I also want the change to occur when leaving the textbox, using the #blur event. I'd like to see what ways this can be done.
I read these materials:
https://codingexplained.com/coding/front-end/vue-js/array-change-detection
https://v2.vuejs.org/v2/guide/list.html
But it seems my example is a bit more complex, as it has indexes associated, and the arrays have complex objects.
Update 4/12/2018
Found out that in my addItem() that I had:
item = this.conditionItems[this.conditionItems.length - 1].item);
to
item = JSON.parse(JSON.stringify(this.conditionItems[this.conditionItems.length - 1].item));
I was thinking the sync modifier in the answer below was causing problems because it duplicated all items. But that's not the case. I was copying a vue object (including the observable properties), which caused it to happen. The JSON parse and JSON stringify methods only copies the properties as a normal object, without the observable properties. This was discussed here:
https://github.com/vuejs/Discussion/issues/292
The problem is that props flow in one direction, from parent to child.
Setting the value using v-model in child won't affect parent's data.
Vue has a shortcut to update parent's data more easily. It's called .sync modifier.
Here's how.
In sub-comp.vue
<template>
<div>
<input type="text" class="form-control" :value="textA" #input="$emit('update:textA', $event.target.value)" >
<input type="text" class="form-control" :value="textB" #input="$emit('update:textB', $event.target.value)">
<input type="text" class="form-control" :value="textC" #input="$emit('update:textC', $event.target.value)">
</div>
</template>
<script>
export default {
// remains the same
}
</script>
add .sync when you add the props
<sub-comp
:textA.sync="listItem.item.textA" // this will have the same effect of v-on:update:textA="listItem.item.textA = $event"
:textB.sync="listItem.item.textB"
:textC.sync="listItem.item.textC"
/>
update:
if you have reactivity problem, don't use .sync, add a custom event and use $set
<sub-comp
:textA="listItem.item.textA" v-on:update:textA="$set('listItem.item','textA', $event)"
/>

Input-fields as components with updating data on parent

I'm trying to make a set of components for repetitive use. The components I'm looking to create are various form fields like text, checkbox and so on.
I have all the data in data on my parent vue object, and want that to be the one truth also after the user changes values in those fields.
I know how to use props to pass the data to the component, and emits to pass them back up again. However I want to avoid having to write a new "method" in my parent object for every component I add.
<div class="vue-parent">
<vuefield-checkbox :vmodel="someObject.active" label="Some object active" #value-changed="valueChanged"></vuefield-checkbox>
</div>
My component is something like:
Vue.component('vuefield-checkbox',{
props: ['vmodel', 'label'],
data(){
return {
value: this.vmodel
}
},
template:`<div class="form-field form-field-checkbox">
<div class="form-group">
<label>
<input type="checkbox" v-model="value" #change="$emit('value-changed', value)">
{{label}}
</label>
</div>
</div>`
});
I have this Vue object:
var vueObject= new Vue({
el: '.vue-parent',
data:{
someNumber:0,
someBoolean:false,
anotherBoolean: true,
someObject:{
name:'My object',
active:false
},
imageAd: {
}
},
methods: {
valueChange: function (newVal) {
this.carouselAd.autoOrder = newVal;
}
}
});
See this jsfiddle to see example: JsFiddle
The jsfiddle is a working example using a hard-coded method to set one specific value. I'd like to eighter write everything inline where i use the component, or write a generic method to update the parents data. Is this possible?
Minde
You can use v-model on your component.
When using v-model on a component, it will bind to the property value and it will update on input event.
HTML
<div class="vue-parent">
<vuefield-checkbox v-model="someObject.active" label="Some object active"></vuefield-checkbox>
<p>Parents someObject.active: {{someObject.active}}</p>
</div>
Javascript
Vue.component('vuefield-checkbox',{
props: ['value', 'label'],
data(){
return {
innerValue: this.value
}
},
template:`<div class="form-field form-field-checkbox">
<div class="form-group">
<label>
<input type="checkbox" v-model="innerValue" #change="$emit('input', innerValue)">
{{label}}
</label>
</div>
</div>`
});
var vueObject= new Vue({
el: '.vue-parent',
data:{
someNumber:0,
someBoolean:false,
anotherBoolean: true,
someObject:{
name:'My object',
active:false
},
imageAd: {
}
}
});
Example fiddle: https://jsfiddle.net/hqb6ufwr/2/
As an addition to Gudradain answer - v-model field and event can be customized:
From here: https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model
By default, v-model on a component uses value as the prop and input as
the event, but some input types such as checkboxes and radio buttons
may want to use the value prop for a different purpose. Using the
model option can avoid the conflict in such cases:
Vue.component('my-checkbox', {
model: {
prop: 'checked',
event: 'change'
},
props: {
checked: Boolean,
// this allows using the `value` prop for a different purpose
value: String
},
// ...
})
<my-checkbox v-model="foo" value="some value"></my-checkbox>
The above will be equivalent to:
<my-checkbox
:checked="foo"
#change="val => { foo = val }"
value="some value">
</my-checkbox>

Vue.js - Can't properly validate a custom single file component with v-for using vee-validate

I've been building a vue app and I'm currently building a component that has a "Person" object, and a few inputs fields to add information about that person, such as Name, address, email, etc. One of those fields is the mobile number, but a person can have more than one number, so I created a custom component that repeats the input field at will. This is roughly what it looks like. All those inputs are being validated using vee validate. This is roughly what is looks like:
<!--createPerson.vue -->
<div class="form-group">
<input v-model="person.firstName" v-validate="'required'" data-vv-delay="500" name="first-name" type="text" placeholder="First name">
<span v-show="errors.has('first-name')" class="input__error">{{ errors.first('first-name') }}</span>
</div>
<div class="form-group">
<input v-model="person.lastName" v-validate="'required'" data-vv-delay="500" name="last-name" type="text" placeholder="Last name">
<span v-show="errors.has('last-name')" class="input__error">{{ errors.first('last-name') }}</span>
</div>
<repeatable-inputs v-model="person.mobiles" v-validate="'required'" data-vv-value-path="input" data-vv-name="mobile" type="tel" name="mobile" placeholder="Mobile" :inputmode="numeric" link-name="mobile number"></repeatable-inputs>
<div class="form-group">
<input v-model="person.email" v-validate="'required|email'" data-vv-delay="500" name='email' type="text" placeholder="Personal email">
<span v-show="errors.has('email')" class="input__error">{{ errors.first('email') }}</span>
</div>
The person object, under the same createPerson.vue file, has a property called mobiles which starts as an empty array. It also has a validateAll() function, used as described in the vee-validate docs, that performs a validation of all inputs when clicking a "Next" button.
Then, on the repeatableInputs.vue, there's this:
<template>
<div>
<div class="form-group" v-for="(input, index) in inputs">
<input
:type="type"
:name="name+index"
:placeholder="placeholder"
:inputmode="inputmode"
:value="input"
#input="update(index, $event)"
v-focus></input>
</div>
Add another {{linkName}}
</div>
</template>
<script>
export default {
props: {
value: {
type: Array,
default: ['']
},
type: {
type: String,
default: "text"
},
name: String,
placeholder: String,
inputmode: String,
linkName: {
type: String,
default: "input"
}
},
data: function () {
return {
inputs: this.value
}
},
methods: {
add: function () {
this.inputs.push('');
},
update: function(index, e) {
this.inputs[index] = e.target.value;
this.$emit('input', this.inputs);
}
}
}
</script>
To be able to validate these custom inputs in the parent createPerson.vue, using the validateAll() function, the docs state that I must, quoting, Should have a data-vv-value-path attribute which denotes how to access the value from within that component (Needed for validateAll calls).
And this is where I got stuck. I'm not sure that that vv-path must point to, and I tried using 'value', ' input', 'inputs', creating a watch function, and a few other things that didn't even make much sense. I've found a git issue with validating custom inputs that used v-for, but that has apparently since been fixed.
Data-vv-value-path should point to where the data is inside the component state. On your input you can bind the input content to data with a v-model -attribute and then the validator knows which property of the child component it needs to validate.
So data-vv-value-path points to the data inside the child component and the data will be automatically updated when bound with v-model.

Categories

Resources