I already checked about other questions, and have read about the “in-place patch” feature, so I tried to add a key to the v-for but still without success, can someone help me?
Here is my current code:
// THE COMPONENT
Vue.component('host-query', {
props : {
"queryvalue" : { type : Object, default : {} },
},
template : '<div class="input-group">' +
'<input class="form-control input-sm col-sm-2" v-bind:class="{ wrongInput : inputError }" v-bind:value="setInput(queryvalue)" @keyup="keyPressed" @input="updateInput($event.target.value)">' +
'<span class="input-group-btn">' +
'<button class="btn btn-sm btn-danger" @click="deleteQuery"> X </button> ' +
'</span>' +
'</div>',
data() {
return {
inputError : false,
keyPressTimeout : null,
inputValue : ''
}
},
methods : {
deleteQuery() {
this.$emit('delete-query');
},
setInput(objValue) {
if (!this.inputValue) {
this.inputValue = JSON.stringify(objValue);
}
return this.inputValue;
},
keyPressed() {
clearTimeout(this.keyPressTimeout);
this.keyPressTimeout = setTimeout(this.validateAndUpdateInput, 1000);
},
validateAndUpdateInput() {
let jsonValue = null;
try {
jsonValue = JSON.parse(this.inputValue);
if (Object.keys(jsonValue).length == 1) {
this.inputError = false;
this.inputValue = '';
this.$emit('input', jsonValue);
} else {
this.inputError = true;
}
} catch (e) {
this.inputError = true;
}
},
updateInput(value) {
this.inputValue = value;
}
}
});
// HERE IS THE HTML
<div class="box host-selector-query-container" v-for="(queryObj, hostQueryIndex) in bundle.hostSelector" v-bind:key="hostQueryIndex">
<host-query v-model="queryObj.query"
v-bind:queryvalue="queryObj.query"
v-bind:index="hostQueryIndex"
@delete-query="removeHostQuery(bundle, hostQueryIndex)">
</host-query>
</div>
// AND THE DELETE QUERY FUNCTION
removeHostQuery (bundle, index) {
bundle.hostSelector.splice(index, 1);
},
I console logged the value of the array before and after the splice, and the right elements are being removed, but in the display shows wrong, always last element removed, what am I missing? Thanks!
It's because of key
. When you use your loop's index as the key
, you tell Vue that your elements are identified by their index.
When you remove an item of your array, you shift every index from the removal point up by one, which means only one index disappears from the array: the last one.
Since Vue is identifying your elements by index, the element with the last index is removed.
You should use as key an attribute which uniquely identifies the element, not the index.