Vue component data property not updating after parent data changes - vue.js

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>

Related

How to rotate single chevron on accordion in vue?

I am using vue chevron in accordion inside for loop. When I am clicking a single dropdown, all other chevrons are rotating. How to rotate the specific chevron for the clicked dropdown in vue ? I am using vue chevron package from https://ispal.github.io/vue-chevron/ . My dropdown looks like this -
My vue code:
<div class="accordion" id="accordionExample">
<div
v-for="(data, index) in topicList"
:key="index"
class="card"
>
<div class="card_header" id="headingOne">
<h2 class="mb-0">
<div
class="btn btn-topic example text-left collapsed"
#click="toggle"
type="button"
data-toggle="collapse"
:data-target="'#collapseOne' + index"
aria-expanded="true"
aria-controls="collapseOne"
>
<vue-chevron
:point-down="pointDown"
:duration="duration"
:thickness="thickness"
:angle="angle"
:round-edges="roundEdges"
/>
{{ data.title }}
</div>
</h2>
</div>
<div
:id="'collapseOne' + index"
class="collapse"
aria-labelledby="headingOne"
data-parent="#accordionExample"
>
<div class="card-body">
<ul
v-for="(data, index) in topicList[index].lessons"
:key="index"
#click="getContent(data.lessonId)"
class="list-group py-1"
>
<li class="list-group-item list-style">
{{ data.title }}
</li>
</ul>
</div>
</div>
</div>
</div>
<script>
import VueChevron from "vue-chevron"
export default{
components:{ VueChevron }
data(){
return{
pointDown: false,
thickness: 8,
duration: 500,
angle: 40,
roundEdges: true,
easing: function n(t) {
return t;
}
}
methods: {
toggle() {
this.pointDown = !this.pointDown;
},
}
}
courseAccess() {
this.$axios
.get(this.$api + "api/v1/courses/" + this.courseId, {
headers: {
Authorization: "Bearer " + localStorage.getItem("_utoken"),
},
})
.then((response) => {
// this.topicList = response.data.data.topics.map((element) => {
// return { ...element, pointDown: true };
// });
this.topicList = response.data.data.topics
this.firstTopic = response.data.data.topics[0].lessons[0].lessonId;
this.getFirstContent(this.firstTopic);
this.loadTopics = true;
});
},
All vue-chevron are binding there point-down prop to the same boolean. You could try to use an array of boolean instead and change your toggle method.
<div class="accordion" id="accordionExample">
<div
v-for="(data, index) in topicList"
:key="index"
class="card"
>
<div class="card_header" id="headingOne">
<h2 class="mb-0">
<div
class="btn btn-topic example text-left collapsed"
#click="toggle(index)"
type="button"
data-toggle="collapse"
:data-target="'#collapseOne' + index"
aria-expanded="true"
aria-controls="collapseOne"
>
<vue-chevron
:point-down="pointDown[index]"
:duration="duration"
:thickness="thickness"
:angle="angle"
:round-edges="roundEdges"
/>
{{ data.title }}
</div>
</h2>
</div>
<div
:id="'collapseOne' + index"
class="collapse"
aria-labelledby="headingOne"
data-parent="#accordionExample"
>
<div class="card-body">
<ul
v-for="(data, index) in topicList[index].lessons"
:key="index"
#click="getContent(data.lessonId)"
class="list-group py-1"
>
<li class="list-group-item list-style">
{{ data.title }}
</li>
</ul>
</div>
</div>
</div>
</div>
<script>
import VueChevron from "vue-chevron"
export default{
components:{ VueChevron }
data(){
return{
pointDown: [],
thickness: 8,
duration: 500,
angle: 40,
roundEdges: true,
easing: function n(t) {
return t;
}
}
methods: {
toggle(index) {
this.pointDown[index] = !this.pointDown[index];
},
}
}
EDIT
The problem discussed in the comments could be caused by reactivity issues. To solve these we are trying to initialize pointDown with an array of the correct size.
courseAccess() {
this.$axios
.get(this.$api + "api/v1/courses/" + this.courseId, {
headers: {
Authorization: "Bearer " + localStorage.getItem("_utoken"),
},
})
.then((response) => {
// this.topicList = response.data.data.topics.map((element) => {
// return { ...element, pointDown: true };
// });
this.topicList = response.data.data.topics;
this.pointDown = new Array(this.topicList.length).fill(false);
this.firstTopic = response.data.data.topics[0].lessons[0].lessonId;
this.getFirstContent(this.firstTopic);
this.loadTopics = true;
});
},

Bind class item in the loop

i want to bind my button only on the element that i added to the cart, it's working well when i'm not in a loop but in a loop anything happen. i'm not sure if it was the right way to add the index like that in order to bind only the item clicked, if i don't put the index every button on the loop are binded and that's not what i want in my case.
:loading="isLoading[index]"
here the vue :
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" #click="addToCart(product)" :loading="isLoading[index]"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
here the data :
data () {
return {
products : [],
isLoading: false,
}
},
here my add to cart method where i change the state of isLoading :
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
You can change your isLoading to an array of booleans, and your addToCart method to also have an index argument.
Data:
return {
// ...
isLoading: []
}
Methods:
addToCart(product, index) {
// ...
}
And on your button, also include index:
#click="addToCart(product, index)"
By changing isLoading to an empty array, I don't think isLoading[index] = true will be reactive since index on isLoading doesn't exist yet. So you would use Vue.set in your addToCart(product, index) such as:
this.$set(this.isLoading, index, true)
This will ensure that changes being made to isLoading will be reactive.
Hope this works for you.
add on data productsLoading: []
on add to cart click, add loop index to productsLoading.
this.productsLoading.push(index)
after http request done, remove index from productsLoading.
this.productsLoading.splice(this.productoading.indexOf(index), 1)
and check button with :loading=productsLoading.includes(index)
You can create another component only for product card,
for better option as show below
Kindly follow this steps.
place the content of card in another vue component as shown below.
<!-- Product.vue -->
<template>
<div class="card">
<div class="card-image">
<figure class="image is-4by3">
<img src="" alt="Placeholder image">
</figure>
</div>
<div class="card-content">
<div class="content">
<div class="media-content">
<p class="title is-4">{{product.name}}</p>
<p class="subtitle is-6">Description</p>
<p>{{product.price}}</p>
</div>
</div>
<div class="content">
<b-button class="is-primary" #click="addToCart(product)" :loading="isLoading"><i class="fas fa-shopping-cart"></i> Ajouter au panier</b-button>
</div>
</div>
</div>
</templete>
<script>
export default {
name: "Product",
data() {
return {
isLoading: false
}
},
props: {
product: {
type: Object,
required: true
}
},
methods: {
addToCart(product) {
this.isLoading = true
axios.post('cart/add-to-cart/', {
data: product,
}).then(r => {
this.isLoading = false
}).catch(e => {
this.isLoading = false
});
}
}
}
</script>
Change your component content as shown below.
<template>
<div class="container column is-9">
<div class="section">
<div class="columns is-multiline">
<div class="column is-3" v-for="(product, index) in computedProducts">
<product :product="product" />
</div>
</div>
</div>
</div>
</templete>
<script>
import Product from 'path to above component'
export default {
components: {
Product
}
}
</script>
so in the above method you can reuse the component in other components as well.
Happy coding :-)

Click Event on Dynamically Generated Button Don't get fired in Vue

I am adding a button dynamically and attaching the click event but it doesn't seem to fire.
I see something similar on link below but its not exactly what I am looking for.
Vue: Bind click event to dynamically inserted content
let importListComponent = new Vue({
el: '#import-list-component',
data: {
files: [],
},
methods: {
// more methods here from 1 to 5
//6. dynamically create Card and Commit Button
showData: function (responseData) {
let self = this;
responseData.forEach((bmaSourceLog) => {
$('#accordionOne').append(`<div class="main-card mb-1 card">
<div class="card-header" id=heading${bmaSourceLog.bmaSourceLogId}>
${bmaSourceLog.fileName}
<div class="btn-actions-pane-right actions-icon-btn">
<input type="button" class="btn btn-outline-primary mr-2" value="Commit" v-on:click="commit(${bmaSourceLog.bmaSourceLogId})" />
<a data-toggle="collapse" data-target="#collapse${ bmaSourceLog.bmaSourceLogId}" aria-expanded="false" aria-controls="collapse${bmaSourceLog.bmaSourceLogId}" class="btn-icon btn-icon-only btn btn-link">
</a>
</div>
</div>
<div id="collapse${ bmaSourceLog.bmaSourceLogId}" class="collapse show" aria-labelledby="heading${bmaSourceLog.bmaSourceLogId}" data-parent="#accordionOne">
<div class="card-body">
<div id="grid${ bmaSourceLog.bmaSourceLogId}" style="margin-bottom:30px"></div>
</div>
</div>
</div>`);
});
},
//7. Commit Staging data
commit: function (responseData) {
snackbar("Data Saved Successfully...", "bg-success");
},
}});
I am adding button Commit as shown in code and want commit: function (responseData) to fire.
I was able to achieve this by pure Vue way. So my requirement was dynamically add content with a button and call a function from the button. I have achieved it like so.
Component Code
const users = [
{
id: 1,
name: 'James',
},
{
id: 2,
name: 'Fatima',
},
{
id: 3,
name: 'Xin',
}]
Vue.component('user-component', {
template: `
<div class="main-card mb-1 card">
<div class="card-header">
Component Header
<div class="btn-actions-pane-right actions-icon-btn">
<input type="button" class="btn btn-outline-primary mr-2" value="Click Me" v-on:click="testme(user.id)" />
</div>
</div>
<div class="card-body">
{{user.name}}
</div>
<div class="card-footer">
{{user.id}}
</div>
</div>
`
,props: {
user: Object
}
,
methods: {
testme: function (id) {
console.log(id);
}
}});
let tc = new Vue({
el: '#test-component',
data: {
users
},});
HTML
<div id="test-component">
<user-component v-for="user in users" v-bind:key="user.id" :user="user" />
</div>

To do List with Vue js 2 using component or v-model

Hello I have here one code with two "todo list" implementations in Vuejs but I have a problem.
1 Using a vue component i am getting a waring about how to use the parent variable.
2 Doing it on the main function I cannot keep the old value for the discard implementation.
please find the working code
Running! todo list in codepen
Vue.component('ntodo-item', {
template: '\
<transition name="fade">\
<div id="if" class="row" v-if="edit">\
<div class="col-md-7">\
<input class="form-control" v-model="title">\
</div>\
<div id="sssss" class="col-md-5">\
<button class="btn btn-danger roundButton" v-on:click="$emit(\'edit\')">Discard</button>\
<button class="btn btn-success roundButton" v-on:click="updateValue">Save</i></button>\
</div>\
</div>\
<div id="else" class="row" v-else>\
<div class="col-md-7">\
{{ title }}\
</div>\
<div id="ssaaas" class="col-md-5">\
<button class="btn btn-danger roundButton" v-on:click="$emit(\'remove\')">Remove</button>\
<button id="aaa" class="btn btn-default roundButton" v-on:click="$emit(\'edit\')">Edit</button>\
</div>\
</div>\
</transition>\
',
props: [
'title' ,
'edit'
],
methods: {
updateValue: function () {
this.$emit('input', this.title);
}
}
})
var app14 = new Vue({
el: '#app-14',
data: {
newTodoText: '',
newTodoText2: '',
todos: [
{
id: 1,
title: 'Do the dishes',
edit:0
},
{
id: 2,
title: 'Take out the trash',
edit:0
},
{
id: 3,
title: 'Mow the lawn',
edit:0
}
],
todos2: [
{
id: 1,
title: 'Do the dishes',
edit:0
},
{
id: 2,
title: 'Take out the trash',
edit:0
},
{
id: 3,
title: 'Mow the lawn',
edit:0
}
],
nextTodoId: 4,
nextTodoId2: 4
},
methods: {
addNewTodo: function () {
this.todos.push({
id: this.nextTodoId++,
title: this.newTodoText,
edit:0
})
this.newTodoText = ''
this.todos = _.orderBy(this.todos, 'id', 'desc');
},
editTodo: function (item){
// console.log(item.title)
item.edit^= 1
},
updateValue: function (item, newValue){
item.title=newValue
item.edit^= 1
},
addNewTodo2: function () {
this.todos2.push({
id: this.nextTodoId2++,
title: this.newTodoText2,
edit:0
})
this.newTodoText2 = ''
this.todos2 = _.orderBy(this.todos2, 'id', 'desc');
},
editTodo2: function (item){
console.log(item.title)
item.edit^= 1
},
deleteTodo2: function (item){
this.todos2.splice(item.id, 1);
},
updateValue2: function(text){
console.log(text);
}
}
})
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s, transform 0.3s;
transform-origin: left center;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
opacity: 0;
transform: scale(0.5);
}
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<div class="col-md-12">
<div class="graybox">
<h5>app14</h5>
<div id="app-14">
`enter code here`<div class="row">
<div class="col-md-6">
<h5> todo list using "ntodo-item" component</h5>
<p>This one show me a warning because the child cannot edit the va passed by the parent but it is working and spected</p>
<input class="form-control"
v-model="newTodoText"
v-on:keyup.enter="addNewTodo"
placeholder="Add a todo"
>
<hr>
<ul>
<li
is="ntodo-item"
v-for="(todo, index) in todos"
v-bind:key="todo.id"
v-bind:title="todo.title"
v-bind:edit="todo.edit"
v-on:input="updateValue(todo, $event)"
v-on:remove="todos.splice(index, 1)"
v-on:edit="editTodo(todo)"
></li>
</ul>
</div>
<div class="col-md-6">
<h5> todo list update</h5>
<p> This one is working without any warn but I dont know how to discard changes. I dont want to create a temp var because I want to be able to edit all of them at the same time. </p>
<input v-model="newTodoText2"
v-on:keyup.enter="addNewTodo2"
placeholder="Add a todo"
class="form-control"
>
<hr>
<ul>
<transition-group name="fade" >
<li v-for="(todo2, index) in todos2":key="todo2.id">
<div id="if" class="row" v-if="todo2.edit">
<div class="col-md-7">
<input class="form-control" ref="todo2" v-model="todo2.title">
</div>
<div id="sssss" class="col-md-5">
<button class="btn btn-success roundButton" v-on:click="editTodo2(todo2)">ok</button>
</div>
</div>
<div id="else" class="row" v-else>
<div class="col-md-7">
{{todo2.title}}
</div>
<div id="ssaaas" class="col-md-5">
<button class="btn btn-danger roundButton" v-on:click="todos2.splice(index, 1)">Remove</button>
<button id="aaa" class="btn btn-default roundButton" v-on:click="editTodo2(todo2)">Edit</button>
</div>
</div>
</li>
</transition>
</ul>
</div>
</div>
</div>
</div>
</div>
.
Echoing my comment:
Create a local variable copy of your title prop and emit that variable's changes on edit. If they discard the edit just reset the local variable to the value of the title prop. Working example on CodeSandbox here.
Todo Item Component
<button class="btn btn-danger roundButton" #click="discardEdit">Discard</button>
...
data() {
return {
// our local copy
localTitle: null,
};
},
mounted() {
this.localTitle = this.title;
},
methods: {
updateValue: function() {
this.$emit("input", this.localTitle);
},
discardEdit: function() {
// just set local back to title prop value
this.localTitle = this.title;
this.$emit('edit');
},
}

Can't get a reset button to clear out a checkbox

I'm using Vue.js v2 and I've defined a single-file component, RegionFacet.vue. It lists some regions that relate to polygons on a map (click a value, the corresponding polygon appears on the map).
Separately, I have a reset button. When that gets clicked, I call a method in RegionFacet to unselect any checkboxes displayed by RegionFacet. The model does get updated, however, the checkboxes remain checked. What am I missing?
<template>
<div class="facet">
<div class="">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<a data-toggle="collapse"v-bind:href="'#facet-' + this.id"><h4 class="panel-title">Regions</h4></a>
</div>
<div v-bind:id="'facet-' + id" class="panel-collapse collapse in">
<ul class="list-group">
<li v-for="feature in content.features" class="list-group-item">
<label>
<input type="checkbox" class="rChecker"
v-on:click="selectRegion"
v-bind:value="feature.properties.name"
v-model="selected"
/>
<span>{{feature.properties.name}}</span>
</label>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: ['content'],
data: function() {
return {
id: -1,
selected: []
}
},
methods: {
selectRegion: function(event) {
console.log('click: ' + event.target.checked);
if (event.target.checked) {
this.selected.push(event.target.value);
} else {
var index = this.selected.indexOf(event.target.value);
this.selected.splice(index, 1);
}
this.$emit('selection', event.target.value, event.target.checked);
},
reset: function() {
this.selected.length = 0;
}
},
created: function() {
this.id = this._uid
}
}
</script>
<style>
</style>
You are directly setting the array length to be zero, which cannot be detected by Vue, as explained here: https://v2.vuejs.org/v2/guide/list.html#Caveats
Some more info: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
To overcome this, you may instead set the value of this.selected as follows:
reset: function() {
this.selected = [];
}