V-model inside v-for is filling all the inputs - vue.js

In few words I have multiple Todolists, once I try to post a new Todo inside the Todolist all the inputs of other Todolists gets fill in with the same words. How can I solve this?
Edit: I can post a new todo without problems and it will appear on the relative todolist (see addTodo method). The ONLY problem is that the v-model is for all the todolists on the field, not only for the one I'm writing in, so as soon as I start to write inside an input I got all the inputs filled.
<div class="todolist" v-for="todolist in todolists" :key="todolist.id">
<div class="td-title">
<h5 class="text-center m-0 py-2 text-light">
{{ todolist.title }}
</h5>
</div>
<form
#submit.prevent="addTodo(todolist.id)"
class="td-inputs d-flex align-items-center justify-content-center"
>
// this is the v-model
<input v-model="todo.title" class="px-2" type="text" />
<button type="submit">
<i class="fas fa-plus fa-2x"></i>
</button>
</form>
<div>
<div v-for="todo in todolist.todos" :key="todo.id" class="todo">
{{ todo.title }}
</div>
<div>
<i class="fas fa-times" #click="cancel(todolist.id)"></i>
</div>
</div>
</div>
data
data() {
return {
todolists: [],
loading: true,
todo: {
title: "",
todolist_id: "",
user_id: ""
},
};
},
Methods
getTodoLists() {
axios
.get("http://127.0.0.1:8000/api/todolists")
.then((res) => {
this.todolists = res.data;
this.loading = false;
})
.catch((err) => {
console.log(err);
});
},
cancel(id) {
axios
.delete(`http://127.0.0.1:8000/api/todolists/${id}`)
.then(() => {
this.getTodoLists();
})
.catch((err) => {
console.log(err);
});
},
addTodo(todolist) {
axios
.post(`http://127.0.0.1:8000/api/${todolist}/todos`, this.todo)
.then(() => {
this.todo = {}
this.getTodoLists();
})
.catch((err) => {
console.log(err);
});
},
Like down here: I'm writing on the left input and it shows even on the right input.
SOLVED:
With this computed property (with setter and getter) I solved my problem, now just the input in which I'm typing in is filled, and the todo can be post without a problem.
computed: {
getTitle: {
get: function () {
return "";
},
set: function (value) {
this.todo.title = value;
},
},
},
And this is the v-model with the new computed property instead of todo.title
<form
#submit.prevent="addTodo(todolist.id)"
class="td-inputs d-flex align-items-center justify-content-center"
>
<input v-model="getTitle" class="px-2" type="text" />
<button type="submit">
<i class="fas fa-plus fa-2x"></i>
</button>
</form>

You have a variable in data called "todo" and then you are reusing that variable name inside your inner v-for:
<div v-for="todo in todolist.todos" :key="todo.id" class="todo">
{{ todo.title }}
</div>
I think todo is referring to the todo from your data, not from the v-for. Thus, all todo items refer to the same variable. Try to rename one of them and see if it solves the problem.

You are binding your input to your todo declared data object.
Instead, you should bind your input to your todolist object in this way:
<div class="todolist" v-for="todolist in todolists" :key="todolist.id">
....
<input v-model="todolist.title" class="px-2" type="text" />
....
</div>

SOLVED:
With this computed property (with setter and getter) I solved my problem, now just the input in which I'm typing in is filled, and the todo can be post without a problem.
computed: {
getTitle: {
get: function () {
return "";
},
set: function (value) {
this.todo.title = value;
},
},
},
And this is the v-model with the new computed property instead of todo.title
<form
#submit.prevent="addTodo(todolist.id)"
class="td-inputs d-flex align-items-center justify-content-center"
>
<input v-model="getTitle" class="px-2" type="text" />
<button type="submit">
<i class="fas fa-plus fa-2x"></i>
</button>
</form>

Related

how can I update a vue child-component from the vuex-store

My application shows a window where player can enter name and passcode to enter
When the player exists and has a card, I want to show the card as well.
When the player exists, I make the card visible. Then in 'created'I call fetchSpelerCards. This is successful but shows in the VUE console as pending...
I hope some experienced vue user reads this and can help me with a hint, reference or explanation.
For that I have in the following code:
<h2>Meld je aan</h2>
<form #submit.prevent="register" class="mb-3">
<div class="form-group">
<input type="text" class="form-control m-2" placeholder="naam" v-model="name">
</div>
<div class="form-group">
<input type="text" class="form-control m-2" placeholder="kies inlogcode" v-model="pass_code">
</div>
<button type="submit" #click="checkSpeler()" class="btn btn-primary btn-block" style="color:white">Save</button>
</form>
<p class="alert alert-danger" v-if="errorMessage !== ''"> {{errorMessage}} </p>
<p class="alert alert-success" v-if="successMessage !== ''"> {{successMessage}} </p>
<CardsSpeler v-if="spelerCorrect"></CardsSpeler>
</div>
</template>
The component looks as follows:
<h2>Cards 1</h2>
<form #submit.prevent="addCard" class="mb-3">
<div class="form-group">
<input type="text" class="form-control" placeholder="title" v-model="card.title">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="description" v-model="card.description">
</textarea>
</div>
<div>
<input type="file" v-on:change="onFileChange" ref="fileUpload" id="file_picture_input">
</div>
<button type="submit" class="btn btn-primary btn-block" style="color:white">Save</button>
</form>
<div class="card card-body mb-2" v-for="card in cards" v-bind:key="card.id">
<h3> {{currentSpelerCard.title}} </h3>
<p> {{currentSpelerCard.description}}</p>
<img class="img-circle" style="width:150px" v-bind:src="currentSpelerCard.picture" alt="Card Image">
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
mounted(){
console.log('component mounted');
},
computed: {
...mapState([
'currentSpeler' ,'currentSpelerCard'
]),
},
data() {
return{
cardExists:false,
successMessage:'',
errorMessage:'',
}
},
created(){
this.fetchSpelerCards();
},
methods: {
...mapActions([ 'getGames', 'addGame', 'fetchSpelerCards' ]),
fetchSpelerCards(){
this.$store.dispatch('fetchSpelerCards', this.currentSpeler.speler.id )
.then(res => {
this.cardExists = true;
this.successMessage = res;
console.log(res);
})
.catch(err => {
this.errorMessage = err;
this.cardExists = false;
});
},
The corresponding action, in actions.js is:
export const fetchSpelerCards = ({commit}, speler_id) => {
return new Promise((resolve, reject) => {
let status = '';
let data ={};
fetch(`api/cardsBySpeler/${speler_id}`)
.then(res => {
status = res.status;
data = res.json();
})
.then(res=>{
if ( status === 200) {
commit('SET_PLAYER_CARD', data);
resolve('Kaart gevonden');
}
else {
reject('Er is geen kaart beschikbaar')
}
});
})
}
In the vuex-store I see (viewed with VUE add-on of chrome browser):
currentSpelerCard: Promise
Yet, the response of the fetch command was successful, and the card was pulled in, as I see also in the console: status 200, I can see name, title, image address etc..
I was under the assumption that, when the promise eventually resolves, the store is updated and the card becomes available because of the:
computed: { ...mapState([ 'currentSpeler' ,'currentSpelerCard' ]),
Can anyone help me and explain what I am doing wrong?
fetchSpelerCards in Vuex commits SET_PLAYER_CARD with data, this will be a pending promise. You need to await the promise.
You can solve this in a few different ways.
Making the function async and await res.json() would be the easiest.
...
fetch(`api/cardsBySpeler/${speler_id}`)
.then(async res => {
status = res.status;
data = await res.json();
})
...

nesting an object inside an object

Looking for some tips on how to nest objects inside objects using a form. My form currently changes the key and value of an object. However, I'm now wanting a second button to be able to create a child (correct termanology?)form input. below you can see an example. I've spent the morning looking at props but I'm unsure if this is the correct way to go, any suggestions are greatly appriciated
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
<form id="app">
<h1>
Title goes here
</h1>
<hr>
<div class="row">
<div class="col-xs-2">
<button type="button" v-on:click="addNewObject" class="btn btn-block btn-success">
(Add +) Parent
</button>
</div>
<div class="col-xs-10 text_info">
Click 'Add +' to add an object
</div>
</div>
<div v-for="(object, index) in objects">
<div class="row">
<div class="col-xs-1">
<label> </label>
<button type="button" v-on:click="removeObject(index)" class="btn btn-rem btn-block btn-danger">
Delete
</button>
<button type="button" v-on:click="addNewChildObject()" class="btn btn-rem btn-block btn-success btn-suc">
add { }
</button>
</div>
<div class="form-group col-xs-7">
<div class="test">
<select v-model="object.type" class="selectBox classic">
<option value="" disabled selected hidden>Choose Datatype</option>
<option v-for="type in types"> {{ type }}</option>
</select>
<input v-model="object.name" :name="'objects[' + index + '][name]'" type="string" class="form-control" placeholder="Enter key">
<input v-model="object.dataValue" :name="'objects[' + index + '][dataValue]'" type="string" class="form-control" placeholder="Enter value">
</div>
</div>
</div>
</div>
<hr>
<div>
<pre v-if="seen">{{ mappedObjects }}</pre>
</div>
<button type="button" class="btn-primary" v-on:click="seen = !seen">{{ seen ? 'Click to Hide the JSON' : 'Click to Show the JSON' }}</button>
</form>
const getDefaultObject = () => ({
name: '',
dataValue: '',
type: ''
})
const app = new Vue({
el: '#app',
computed: {
mappedObjects() {
return this.objects.map(({
name,
dataValue,
type
}) => ({
[name]: dataValue,
type
}))
}
},
props: {
},
data() {
return {
seen: false,
types: ['string', 'character', 'number', 'int', 'floating-point', 'boolean', 'date;'],
objects: []
}
},
methods: {
addNewObject: function() {
this.objects.push(getDefaultObject())
},
removeObject: function(index) {
Vue.delete(this.objects, index);
},
addNewChildObject: function () {
}
}
})
If you want n forms with n children just create a model for it following that same structure and pass props to the form.
parent = {
...props,
children: []
}
child = {
...props
}
If the forms are too complex (or a little complex really), split them in separate components and pass children as props.
If you want to use the same form both in parent and children take a look at slots, they will allow you to create flexible layouts.

Checking checkbox programmatically doesn't render the change when using nested arrays with objects

сеI have an array with categories. Each category has children.
When a parent is checked/unchecked, its children must be checked/unchecked as well. If all children are checked, the parent must be checked as well.
Vue updates the fields as expected, but doesn't re-render. I cannot understand why.
Here is my code:
<template>
<div class="card">
<div class="card-body">
<ul class="list-tree">
<li v-for="category in categories" :key="category.id" v-show="category.show">
<div class="custom-control custom-checkbox">
<input :id="'category-' + category.id"
v-model="category.checked"
#change="checkParent(category)"
type="checkbox"
class="custom-control-input" />
<label class="custom-control-label"
:for="'category-' + category.id">
{{ category.name }}
</label>
</div>
<ul>
<li v-for="child in category.children" :key="child.id" v-show="child.show">
<div class="custom-control custom-checkbox">
<input :id="'category-' + child.id"
v-model="child.checked"
#change="checkChild(child, category)"
type="checkbox"
class="custom-control-input" />
<label class="custom-control-label" :for="'category-' + child.id">
{{ child.name }}
<small class="counter">({{ child.products_count }})</small>
</label>
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
</template>
export default {
data () {
return {
categories: [],
listItemTemplate: { show: true, markedText: null, checked: false }
}
},
methods: {
checkParent (category) {
category.children.forEach(child => {
child.checked = category.checked
})
},
initializeCategories () {
this.categories = []
this.originalCategories.forEach(originalCategory => {
var parent = this.copyObject(originalCategory)
this.categories.push(parent)
parent.children.forEach (child => {
child = this.copyObject(child)
})
})
},
copyObject (category) {
return Object.assign(category, {...this.listItemTemplate})
}
},
computed: {
...mapState({
originalCategories: state => state.categories,
})
},
mounted () {
this.initializeCategories()
}
}
You need to expand your scope, since you are changing it only within checkParent() method, variables that you are making changes to will not have an effect onto components variables.
Use the index instead of value in categories iteration to find correct category, and then apply changes in scope of whole component:
<li v-for="(category, categoryIndex) in categories" :key="category.id" v-show="category.show">
<div class="custom-control custom-checkbox">
<input :id="'category-' + category.id"
v-model="category.checked"
#change="checkParent(categoryIndex)"
type="checkbox"
class="custom-control-input" />
<label class="custom-control-label"
:for="'category-' + category.id">
{{ category.name }}
</label>
</div> <!-- the rest of the code ... -->
And then in component's method:
methods: {
checkParent (categoryIndex) {
let categoryChecked = this.categories[categoryIndex];
this.categories[categoryIndex].children.forEach((child, childIndex) => {
this.categories[categoryIndex].children[childIndex].checked = categoryChecked;
})
},
I fixed it. The problem wasn't related to the checkboxes at all. The problem was related to the way I've created the categories array.
When I initialize the component, I copy the array from vuex and add new properties (like checked) in order to check the children when the parent is checked. I didn't follow the rules for adding new fields, that's why the children wasn't reactive and didn't get checked when the parent was checked.
Thanks a lot for your effort to help me!

Data Reactivity On Post Request Vue

Im having issues with my data not reacting correctly when a new object is added to the array of data. I am currently looping through an array of engagements that belong to a client like this
<div class="row mx-2 px-2 justify-content-between" v-if="!engagementLoaded">
<div class="card mb-3 shadow-sm col-lg-5 col-md-3 p-0" v-for="(engagement, index) in engagement" :key="index">
<div class="d-flex justify-content-between card-header">
<h3 class="m-0 text-muted">{{ index + 1 }}</h3>
<h5 class="align-self-center m-0"><span>Return Type: </span> {{ engagement.return_type }} </h5>
</div>
<div class="card-body text-left p-0 my-1">
<h5 class="p-4"><span>Year: </span> {{ engagement.year }} </h5>
<hr class="my-1">
<h5 class="p-4"><span>Assigned To: </span> {{ engagement.assigned_to }} </h5>
<hr class="my-1">
<h5 class="p-4"><span>Status: </span> {{ engagement.status}} </h5>
</div>
<div class="card-footer d-flex justify-content-between">
<router-link to="#" class="btn">View</router-link>
<router-link to="#" class="btn">Edit</router-link>
</div>
</div>
</div>
Everything works fine until I add a new engagement to the array. My AddEngagement Component is seperate but this is the form and script for it.
<form #submit.prevent="addEngagement" class="d-flex-column justify-content-center">
<div class="form-group">
<select class="form-control mb-3" id="type" v-model="engagement.return_type">
<option v-for="type in types" :key="type.id" :value="type">{{ type }}</option>
</select>
<input type="text" class="form-control mb-3" placeholder="Year" v-model="engagement.year">
<input type="text" class="form-control mb-3" placeholder="Assign To" v-model="engagement.assigned_to">
<input type="text" class="form-control mb-3" placeholder="Status" v-model="engagement.status">
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary d-flex justify-content-start">Create</button>
<router-link v-bind:to="'/client/' +client.id+ '/engagements'" class="btn btn-secondary float-right">Dismiss</router-link>
</div>
</div>
</form>
This is the addEngagement Method for the form
methods: {
addEngagement(e) {
if(!this.engagement.return_type || !this.engagement.year ){
return
} else {
this.$store.dispatch('addEngagement', {
id: this.idForEngagement,
client_id: this.client.id,
return_type: this.engagement.return_type,
year: this.engagement.year,
assigned_to: this.engagement.assigned_to,
status: this.engagement.status,
})
e.preventDefault();
}
e.preventDefault();
this.engagement = ""
this.idForEngagement++
this.$router.go(-1);
},
},
I think the issue is happening here but im not sure
this.$router.go(-1);
Ive tried this as well
this.$router.push({path: 'whatever route'})
and it did not change either
Somehow I need the parent component EngagementsList to react correctly to my newly added engagement that is submitted from the AddEngagement componenet if that makes sense..
here is the code for the addEngagement in the Vuex
addEngagement(context, engagement) {
axios.post(('/engagements'), {
client_id: engagement.client_id,
return_type: engagement.return_type,
year: engagement.year,
assigned_to: engagement.assigned_to,
status: engagement.status,
done: false
})
.then(response => {
context.commit('getClientEngagement', response.data)
})
.catch(error => {
console.log(error)
})
},
Although I can't see your code, I'm pretty certain I know the problem. You have an array but it's not reactive to the objects within. This is because Vue doesn't know to observe this array.
If you want your array to be reactive, use Vue.set from within your store model.
Vue.set(this/state, 'array_name', Array<Of objects>)
This will make sure vue watches for changes within the Array.
For your use case, you will need to append the engagement object to the existing array and then use that array:
const engagements = state.engagements
engagements.push(engagement)
Vue.set(state, 'engagements', engagements)
So i've tried different configurations of this. I changed my state description that the v-for is iterating to clientengagements
engagement now equals clientengagements
here is the mutation currently
getClientEngagements(state, engagement, clientengagements) {
state.clientengagements = clientengagements
clientengagements.push(engagement)
Vue.set(state, 'clientengagements', clientengagements)
},
Which is not working. Ive also tried
getClientEngagements(state, clientengagements) {
state.clientengagements = clientengagements
clientengagements.push(engagement)
Vue.set(state, 'clientengagements', clientengagements)
},
Which will tell me that "engagement" is not defined
If anyone is still able to help this is the Action
addEngagement(context, engagement) {
axios.post(('/engagements'), {
client_id: engagement.client_id,
return_type: engagement.return_type,
year: engagement.year,
assigned_to: engagement.assigned_to,
status: engagement.status,
done: false
})
.then(response => {
context.commit('getClientEngagements', response.data)
})
.catch(error => {
console.log(error)
})
},
The response.data is mutating my clientengagements array to just a single object of the newly added engagement..
context.commit('getClientEngagements`, response.data)
Is commiting to this mutation
getClientEngagements(state, engagement, clientengagements) {
state.clientengagements = clientengagements
clientengagements.push(engagement)
Vue.set(state, 'clientengagements', clientengagements)
},

Vue component data property not updating after parent data changes

I have a vue component (card-motor) with a prop named motor:
<div v-for="chunk in chunkDataMotores" class="row">
<div v-for="motor in chunk" class="col-md-6">
<card-motor :motor="motor"></card-motor>
</div>
</div>
Whenever data (motor) changes on the parent, the changes on the data property (id_color, id_motor, nombre _motor, etc...) of the component does not get updated. Here the card-motor component:
<template>
<div class="card" :data-motor-id="id_motor">
<div class="card-header" :style="backgroundColor">
<h4 class="text-center">{{nombre_motor}}<button class="btn btn-dark btn-sm pull-right" :data-motor-id="id_motor" #click="show_modal_colores(id_motor)">Color motor</button></h4>
</div>
<div class="card-body">
<div class="card">
<div class="card-header" role="tab" id="headingOne">
<div class="mb-0">
<a data-toggle="collapse" :href="computedId">
Piezas asociadas {{nombre_motor}} <i class="fa fa-caret-down" aria-hidden="true"></i>
</a>
<button #click="addPieza(id_motor)" class="btn pull-right" title="Añadir pieza nueva al motor"><i class="fa fa-plus text-info" aria-hidden="true"></i></button>
</div>
</div>
<div :id="id_motor" class="collapse" role="tabpanel" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
<ul class="list-group">
<li class="list-group-item" v-for="pieza in piezas_motor">
<span class="badge badge-secondary">{{nombre_motor}}</span> {{pieza.pieza}}
<button class="btn btn-sm btn-danger pull-right"><i class="fa fa-trash" aria-hidden="true"></i></button>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['motor'],
data: function () {
return {
nombre_motor: this.motor.motor,
id_motor: this.motor.id,
id_color: this.motor.color.id,
piezas_motor: this.motor.piezas,
}
},
methods: {
show_modal_colores: function(id){
let $engine = $('#engine-colors');
$engine.data('motor-id', id);
$engine.find('div.color').removeClass('active');
$engine.find('div[data-id="'+this.activeColor+'"]').addClass('active');
$engine.modal('show');
},
addPieza(id) {
let $form = $('#form-pieza');
$form.data('motor-id', id);
$form.modal('show');
}
},
computed: {
computedId: function () {
return '#'+ this.id_motor;
},
backgroundColor: function () {
return 'background-color: '+ this.motor.color.codigo;
},
activeColor: function () {
return this.motor.color.id;
}
},
}
And here the parent code (root component):
Vue.component('card-motor', require('./components/CardMotor.vue'));
var app = new Vue ({
el: '#app',
data: {
dataMotores: [],
dataPuestos: [],
background_style: {
'background-color': ''
}
},
methods: {
makeActiveColor: function(e) {
$(e.currentTarget).closest('.modal-body').find('div.color').removeClass('active');
$(e.currentTarget).closest('div.color').addClass('active');
},
changeColor: function(e) {
let vm = this;
let id=$(e.currentTarget).closest('div.modal-content').find('.active').data('id');
let motor_id = $(e.currentTarget).closest('#engine-colors').data('motor-id');
axios.post('/admin/motores/change-color', {idmotor:motor_id, idcolor: id})
.then(response=>{
this.getData();
$('#engine-colors').modal('hide');
});
},
getData: function(){
axios.get('/admin/motores/api/data')
.then(response => {
this.dataMotores = response.data.motores;
this.dataPuestos = response.data.puestos;
})
.catch();
}
},
computed: {
chunkDataMotores() {
return _.chunk(this.dataMotores, 2);
}
},
created: function() {
this.getData();
}
});
Data returned from the axios call to the server are arrays of objects (getData method). Computed properties updates properly on the component, but not the data property.
You are making copies of your props, so the component renders, make your copies inside data(), but data() is called once, so when the parent component updates the child does not update.
data: function () {
return {
nombre_motor: this.motor.motor,
id_motor: this.motor.id,
id_color: this.motor.color.id,
piezas_motor: this.motor.piezas,
}
},
You can use motors prop directly, like:
<div class="card-header" :style="backgroundColor">
<h4 class="text-center">
{{ motor.motor }}
<button class="btn btn-dark btn-sm pull-right"
:data-motor-id="motor.id"
#click="show_modal_colores(motor.id)">
Color motor
</button>
</h4>
</div>
You need to pass value of dataMotores in components
<card-motor :motor="dataMotores"></card-motor>