Axios making DELETE and GET in the wrong order - javascript

I'm working on a small project in vue.js connected to a lumen API (working).
I currently have a list of students ('Etudiants') in which I can click in the list to select one, and delete it via a button in a toolbar.
When a student is deleted I'm reloading the student list (since it's not up to date anymore), therefore I'm doing 2 api calls via axios.
DELETE http://www.url.com/etudiants (param: idEtudiant)
GET http://www.url.com/etudiants (param: page)
The problem is that my API calls are not done in the right order, as shown here on a screenshot of the calls (with watterfall):
This problem involves 3 vue files.
'Etudiants.vue' and its 2 childs: 'ListeEtudiants.vue' (student list) and 'BarreOutilsEtudiant.vue' (toolbar)
This simple image shows the hierarchy of the 3 files and the order of which everything should execute.
In my case (when it's not working) the action number 3, the axios DELETE, happens in last.
Here are the contents of my files:
Etudiants.vue:
<template>
<div id="etudiants" class="container-fluid h-100">
<div class="row">
<div class="col-3 borderR">
<ListeEtudiants ref="list" #idEtudiantChanged="updateIdEtudiant"/>
</div>
<div class="col-9 bg-light">
<BarreOutilsEtudiant v-if="idEtudiant != null" :idEtudiant="idEtudiant" #delEtudiant="delEtudiant"/>
<InfosEtudiant v-if="idEtudiant != null" :idEtudiant="idEtudiant"/>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
import ListeEtudiants from '#/components/ListeEtudiants.vue'
import InfosEtudiant from '#/components/InfosEtudiant.vue'
import BarreOutilsEtudiant from '#/components/BarreOutilsEtudiant.vue'
export default {
components: {
ListeEtudiants,
InfosEtudiant,
BarreOutilsEtudiant
},
data: function(){
return {
idEtudiant: null
}
},
methods:{
updateIdEtudiant(idEtudiant){
this.idEtudiant=idEtudiant;
},
delEtudiant(){
axios
.delete('http://82ab2617.ngrok.io/etudiants', {params: {"idEtudiant" :this.idEtudiant}})
.then(this.$refs.list.loadList())
.catch(error => console.log(error));
}
}
}
</script>
ListeEtudiants.vue:
<template>
<div id="ListeEtudiants">
<div class="row bg-light">
<!-- Trigger Modal Ajout Etudiant -->
<button class="btn btn-light w-100" data-toggle="modal" data-target="#addModal">
<font-awesome-icon icon="plus" size="1x"/>
<span> Ajouter un Etudiant</span>
</button>
</div>
<ul v-if="etudiants != null" id="list" class="row flex-nowrap list-group list-group-flush pr-0">
<button v-for="etudiant in etudiants.data" v-on:click='$emit("idEtudiantChanged",etudiant.idEtudiant)' class="btn btn-light text-left list-group-item pl-5 py-1">{{ etudiant.nom }} {{ etudiant.prenom }}</button>
</ul>
<ul v-else class="row flex-nowrap list-group list-group-flush pr-0">
</ul>
<div class="row bg-light">
<button class="btn btn-light col-3" v-on:click="page -= 1" :disabled="page === 1 || disabled"><font-awesome-icon icon="chevron-left" size="1x"/></button>
<div class="align-middle col-6 my-auto">{{ page }} / {{ maxPage }}</div>
<button class="btn btn-light col-3" v-on:click="page += 1" :disabled="page === maxPage || disabled"><font-awesome-icon icon="chevron-right" size="1x"/></button>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "ListeEtudiants",
data: function(){
return {
etudiants: null,
maxPage:1,
disabled:false,
page:1,
}
},
methods: {
parseAndDisplay: function(data){
this.etudiants = data;
this.maxPage = data.last_page;
this.page = data.current_page;
this.disabled = false;
},
loadList: function(){
this.disabled = true;
this.etudiants = null;
axios
.get('http://82ab2617.ngrok.io/etudiants', {params: {page:this.page}})
.then(response =>this.parseAndDisplay(response.data))
.catch(error => console.log(error));
}
},
watch: {
'page': function(newVal, oldVal){
if((newVal === 0 && oldVal === 1) || (newVal === this.maxPage+1 && oldVal === this.maxPage)){
this.page = oldVal;
}else{
if(oldVal !== 0 && oldVal !== this.maxPage+1) {
this.loadList();
}
}
}
}
,
mounted() {
this.loadList();
}
}
</script>
BarreOutilsEtudiant.vue:
<template>
<div class="row p-2 navbar-expand navbar-info bg-info">
<button class="btn btn-info mr-5" type="button"><font-awesome-icon icon="download" size="1x"/> Télécharger le Bulletin</button>
<button class="btn btn-info ml-auto" type="button"><font-awesome-icon icon="user-edit" size="1x"/></button>
<button class="btn btn-danger ml-4" v-on:click="$emit('delEtudiant')" type="button"><font-awesome-icon icon="trash-alt" size="1x"/></button>
</div>
</template>
<script>
export default {
name: "BarreOutilsEtudiant"
}
</script>
<style scoped>
</style>
Thank you very much for helping me.

I believe the problem is here:
.then(this.$refs.list.loadList())
That will call loadList immediately and pass the value it returns to then, which isn't what you want.
Instead it should be something like this, wrapping it in a function:
.then(() => this.$refs.list.loadList())

Related

Vue Object not updating with axios POST request

<template>
<div>
<div class="dropdown d-inline-block ml-2">
<button type="button" class="btn btn-sm btn-dual" id="page-header-notifications-dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-on:click="MarkAllAsRead($event)">
<i class="si si-bell"></i>
<span class="badge badge-danger badge-pill" v-if="CountUnread(notifications)">{{ CountUnread(notifications) }}</span>
</button>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right p-0 border-1 font-size-sm" aria-labelledby="page-header-notifications-dropdown">
<div class="p-2 bg-primary text-center">
<h5 class="dropdown-header text-uppercase text-white">Notifications</h5>
</div>
<ul class="nav-items mb-0" style="overflow-y:scroll; height:500px;">
<!-- notifications should have been updated by axios but they never appear -->
<li v-for="notification of notifications">
<div v-if="notification.length">
<notification v-bind:notification="notification[0]"></notification>
</div>
<div v-else>
<notification v-bind:notification="notification"></notification>
</div>
</li>
<div class="p-2 border-top" v-if="hasMore">
<a class="btn btn-sm btn-light btn-block text-center" href="javascript:void(0)" v-on:click="loadMoreNotifications($event)">
<i class="fa fa-fw fa-arrow-down mr-1"></i> Load More..
</a>
</div>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
props:[
'user'
],
data: function() {
return{
notificationsIndex:0,
notifications:[],
hasMore:1
}
},
methods: {
loadNotifications: function(){
var data = {
index: this.notificationsIndex
};
axios.post('/notifications/getAll',data).then( response => {
if(response.data){
if(this.notifications.length==0){
this.notifications=response.data;
console.log(this.notifications);//data fetched here successfully
}
else{
this.notifications.push.apply(this.notifications,response.data);
}
}
else{
this.hasMore = 0;
}
});
console.log(this.notifications);//couldn't find data, just observer object
},
loadMoreNotifications: function(event){
event.preventDefault();
this.notificationsIndex++;
this.loadNotifications();
},
CountUnread: function(notifications){
var count=0;
for(var i=0;i<notifications.length;i++){
if(notifications[i].read_at == null){
count++;
}
}
return count;
},
HasNotification: function(notification){
list = this.notifications.filter(item => {
return item.id == notification.id;
});
return list.length
}
},
created: function(){
this.loadNotifications();
window.Echo.private('App.User.' + this.user.id)
.notification((notification) => {
if(this.HasNotification){
this.notifications.unshift(notification);
}
});
}
}
</script>
And notifications object has nothing in html template as well.
Note: This same code works fine on all pages where I have this only instance of vue. On another page (localhost/horizon)(using laravel horizon package and updating it's layout.blade.php ) where there are two instances of vue, one for notifications and other of Laravel/Horizon, this request returns nothing.
The problem here as #cbaconnier mentioned is that you're using an async function and not waiting for the result.
The console.log() that's failing is due to the fact that it's executed before the post request is retrieved (that's why you're receiving an observer).
The same happens in your created method.
try taking all the code that's dependant on the received notifications into the .then() callback of the axios call.
The problem here was, I was using a bootstrap shipped with app theme I was using and when I installed Horizon and updated Horizon layout.blade.php file according to my customisations, it broke this piece of code because it was using some other bootstrap version and once I removed the bootstrap from the horizon require('bootstrap'); in one of it's app.js file, everything worked fine.

Vue import same component twice/ Vue event from child only to root, not to parent

What I have
I'm importing the same component twice. This component is used to display a dropdown with collections.
When an item in the dropdown is selected, an event is triggered.
The component is imported in list.js and in BulkActions.vue.
The problem
An event is fired when a collection in the dropdown is selected. It then triggers an event using $emit. Somehow this event is only catched in list.blade.php and not in BulkActions.vue.
For both dropdowns (loading from the same component) there should be a different behaviour.
I have no idea why this happens or why the event is only catched at my root.
What I've tried
I've tried to pass an additional prop in the HTML to have a "variable event name", but that didn't work. I've tried various ways of importing the component as well.
Does anyone know how to solve this issue?
The files
list.blade.php:
<div class="media-list-navbar mt-3 mb-3">
<shown-results :text="resultText"></shown-results>
<search-bar #update-filters="updateFilters"></search-bar>
<document-types #update-filters="updateFilters"></document-types>
<collection-dropdown eventname="update-filters"
#update-filters="updateFilters"></collection-dropdown>
<div class="clearfix"></div>
</div>
<bulk-actions #select-all="selectAll"
#deselect-all="deselectAll"
:items="items"
:multiselect="multiSelect"></bulk-actions>
BulkActions.vue
<template>
<div class="multiselect-list-navbar mt-3 mb-3" v-if="multiselect">
<div class="float-left">
<button type="button"
class="btn btn-outline-secondary"
#click="$emit('deselect-all')">
<i class="fas fa-fw fa-times"></i> {{ Lang.get('media/item.index.list.multi-select.deselect-all') }}
</button>
<button type="button"
class="btn btn-outline-secondary"
#click="$emit('select-all')">
<i class="fas fa-fw fa-check"></i> {{ Lang.get('media/item.index.list.multi-select.select-all') }}
</button>
</div>
<bulk-collection
#update-filters="doSomething"></bulk-collection>
<div class="clearfix"></div>
</div>
</template>
<script>
export default {
name: "Bulk",
props: {
multiselect: Boolean,
items: Array
},
components: {
'bulk-collection': () => import('./Collections')
},
methods: {
doSomething() {
console.log(this.items)
}
}
}
</script>
<style scoped>
</style>
list.js
import MediaItem from '../components/MediaItem';
import UploadModal from '../components/media/UploadModal';
import ItemDetail from '../components/media/ItemDetail';
import ShownResults from '../components/media/list/ShownResults';
import SearchBar from '../components/media/list/SearchBar';
import DocumentTypes from '../components/media/list/DocumentTypes';
import {default as CollectionDropdown} from '../components/media/list/Collections';
import Order from '../components/media/list/Order';
import BulkActions from '../components/media/list/BulkActions';
if (document.getElementById('media-list')) {
const mediaList = new Vue({
el: '#media-list',
components: {
MediaItem,
ShownResults,
SearchBar,
UploadModal,
ItemDetail,
DocumentTypes,
CollectionDropdown,
Order,
BulkActions
},
[...]
Collections.vue
<template>
<div class="dropdown float-left">
<button class="btn btn-secondary dropdown-toggle"
type="button"
data-toggle="dropdown">
{{ Lang.get('media/item.index.list.filters.collections.title') }}
</button>
<div class="dropdown-menu" ref="collectionDropdown">
<div class="dropdown-item no-pseudo">
<input type="search"
class="form-control"
name="search"
:placeholder="Lang.get('media/item.index.list.filters.collections.filter')"
v-model="query"
#keyup="search">
</div>
<div class="dropdown-item last-item no-pseudo">
<alert type="warning">
<template v-slot:body>
{{ Lang.get('media/item.index.list.filters.collections.none-filter') }}
</template>
</alert>
</div>
<div v-for="item in list"
class="dropdown-item"
v-if="!item.hidden">
<span class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
name="collection[]"
:checked="item.checked"
:id="item.slug"
:value="item.id"
#change="selectItem">
<label class="custom-control-label" :for="item.slug">
{{ item.name }}
</label>
</span>
</div>
</div>
</div>
</template>
<script>
import Alert from '../../partials/Alert';
export default {
name: "Collections",
components: {
Alert
},
data() {
return {
displayAmount: 10, // amount of items displayed without search
list: [],
query: ''
}
},
computed: {
/**
* Return an array of selected items only
*/
checked() {
return this.list.filter(item => {
return item.checked === true;
})
}
},
methods: {
/**
* Mark an item as selected
*/
selectItem(e) {
let selectedId = e.target.value;
this.markItem(selectedId);
},
/**
* Mark an item from the list as selected
*
* #param {Number} itemId
*/
markItem(itemId) {
this.list.forEach(item => {
if (item.id === parseInt(itemId)) {
item.checked = !item.checked;
}
});
this.$emit('update-filters', {
props: this.checked.map(item => item.id).join(',')
});
},
/**
* Search in the current URL for collection ids
*/
markItemsFromUrl() {
let urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('collection')) {
let urlFilters = urlParams.get('collection').split(','); // split url parameters
urlFilters.forEach(itemId => {
this.markItem(itemId);
});
}
},
},
mounted() {
this.fetchList();
this.markItemsFromUrl();
/**
* Prevent Bootstrap dropdown from closing after clicking inside it
*/
$(this.$refs.collectionDropdown).on('click.bs.dropdown', function (e) {
e.stopPropagation();
});
}
}
</script>
Below is a GIF animation to demonstrate the problem. The first dropdown (the one on the top) has normal behaviour. The second one (that appears later on) does not. When clicking the second one, an event of the first one is happening.

Component's values not being updated

I created a Vue app, where I have a single HTTP request. Once the data returns, I update the profile value. But all components using this value do not get reloaded. Below is the code to better explain what I am trying to accomplish.
I have the main Vue file App.vue:
<template>
<div id="app">
<Navigation />
<Header :profile="profile" />
<About :profile="profile" />
<Services :profile="profile" />
</div>
</template>
<script>
import Navigation from './components/Navigation.vue'
import Header from './components/Header.vue'
import About from './components/About.vue'
import Services from './components/Services.vue'
export default {
name: 'app',
components: {
Navigation,
Header,
About,
Services,
},
data() {
return {
profile: { }
}
},
created() {
this.getUserProfile()
},
methods: {
getUserProfile: async function() {
try {
const response = await fetch('http://localhost:7070/v1/home');
const data = await response.json();
this.profile = data;
} catch (error) {
console.error(error);
}
}
}
}
</script>
<style>
</style>
As you can see, I set the variable profile to empty object at the start. And once the app enters the mounted state, I can the GET request to retrieve the profile data. When I debug, I can clearly see data is not an empty object. The response contains all data.
As you can see from the app file, I import 4 files to add 4 components to the app. All components are done in the same principle.
Here is the navigation.vue content:
<template>
<nav class="navbar navbar-expand-lg navbar-light fixed-top py-3" id="mainNav">
<div class="container">
<a class="navbar-brand js-scroll-trigger" href="#page-top">Home</a>
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto my-2 my-lg-0">
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="#about">About</a>
</li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="#services">Services</a>
</li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="#career">Career</a>
</li>
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="#contact">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
</template>
<script>
</script>
<style scoped>
</style>
Component header.vue:
<template>
<header class="masthead">
<div class="container h-100">
<div class="row h-100 align-items-center justify-content-center text-center">
<div class="col-lg-10 align-self-end">
<h1 class="text-uppercase text-white font-weight-bold">{{ fullName }}</h1>
<h2 class="text-uppercase text-white font-weight-bold">{{ profession }}</h2>
<hr class="divider my-4">
</div>
<div class="col-lg-8 align-self-baseline">
<p class="text-white-75 font-weight-light mb-5">{{ oneLiner }}</p>
<a class="btn btn-primary btn-xl js-scroll-trigger" href="#about">Find Out More</a>
</div>
</div>
</div>
</header>
</template>
<script>
export default {
props: {
profile: Object
},
computed: {
fullName: function () {
if (typeof(profile) == 'undefined') {
return 'Jernej Klancic';
}
return profile.firstname + ' ' + profile.lastname;
},
profession: function() {
if (typeof(profile) == 'undefined') {
return 'Developer';
}
return profile.profession;
},
oneLiner: function() {
if (typeof(profile) == 'undefined') {
return '';
}
return profile.oneLiner;
}
}
}
</script>
<style scoped>
</style>
Component about.vue:
<template>
<section class="page-section bg-primary" id="about">
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-8 text-center">
<h2 class="text-white mt-0">About</h2>
<hr class="divider light my-4">
<p class="text-white-50 mb-4">{{ aboutMe }}</p>
<a class="btn btn-light btn-xl js-scroll-trigger" href="#services">Expertise</a>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: {
profile: Object
},
computed: {
aboutMe: function () {
if (typeof(profile) == 'undefined') {
return '';
}
return profile.aboutMe;
}
}
}
</script>
<style scoped>
</style>
Component service.vue:
<template>
<section class="page-section" id="services">
<div class="container">
<h2 class="text-center mt-0">At Your Service</h2>
<hr class="divider my-4">
<div class="row">
<div v-for="skill in skills" v-bind:key="uuid" class="col-lg-3 col-md-6 text-center">
<div class="mt-5">
<i v-bind:class="fontAwesomeDecorator(skill)"></i>
<h3 class="h4 mb-2">{{ skill.type }}</h3>
<p class="text-muted mb-0">{{ skillLevel(skill) }}</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="mt-5">
<i class="fas fa-4x fa-laptop-code text-primary mb-4"></i>
<h3 class="h4 mb-2">Other</h3>
<p class="text-muted mb-0">Always eager to learn new language or framework</p>
</div>
</div>
</div>
</div>
</section>
</template>
<script>
export default {
props: {
profile: Object
},
computed: {
skills: function () {
if (typeof(profile) == 'undefined') {
return [];
}
return profile.favoriteExpertise.proficient.slice(0, 3);
}
},
methods: {
fontAwesomeDecorator: function(skill) {
var style = ['fab', 'fa-4x', 'text-primary', 'mb-4'];
var uppercase = skill.type.toUpperCase();
if (uppercase === 'JAVA') {
style.push('fa-java');
}
if(uppercase === 'JAVASCRIPT') {
style.push('fa-js');
}
if(uppercase === 'ANDROID') {
style.push('fa-android');
}
return style;
},
skillLevel: function(skill) {
switch(skill.rating) {
case 10:
return `Living and breathing ${skill.type} code`;
case 9:
return `${skill.type} marksmen`;
case 8:
return `Bug slayer in the ${skill.type} realm`;
case 7:
return `${skill.type} fanboy`;
case 6:
return `Level ${skill.rating} ${skill.type} wizard`;
case 5:
return `${skill.type} nerd`;
default:
return `${skill.type} motivator stage ${skill.type}`;
}
}
}
}
</script>
<style scoped>
</style>
Can anyone tell what could be wrong? Should I change my approach? Is there a better way to do this in Vue? As said, I retrieve the profile JSON object from the backend. I reassign the profile variable by using this.profile = data; in App.vue. Should this not trigger a reload of data?
You need to access the profile prop using this.profile within the JavaScript portion of you component.
For example, this won't work:
skills: function () {
if (typeof(profile) == 'undefined') {
return [];
}
return profile.favoriteExpertise.proficient.slice(0, 3);
}
Instead of just profile you need to write this.profile.
The ability to drop the this. in the template does not carry over to elsewhere. That's specifically a feature of the templating language. In the <script> section you need to include the this. just like you would in any other JavaScript code. Props, data, computed properties and methods are all accessed as properties of the Vue instance in this way.

Error on saving to local storage for Vue.js

In my Vue JS app I am trying to save data I get back from a rest api into a list component but I am getting the following error:
Error in mounted hook: "SyntaxError: Unexpected token u in JSON at position 0"
I can't see what could be causing this?
Component:
<template>
<div class="mb-5 mt-5 container">
<div class="list-group">
<a href="#" class="list-group-item list-group-item-action active">
My List
<span class="badge badge-light">{{List.length}}</span>
</a>
<a
href="#"
class="list-group-item list-group-item-action"
v-for="(result, index) in List"
:key="index"
>
{{result.collectionName}}
<br>
<b>{{result.artistName}}</b>
<br>
<div class="row">
<div class="col-md-6">
<button
class="btn btn-success btn-sm btn-block"
v-on:click="removeElement(index)"
>Remove</button>
</div>
<div class="col-md-6">
<button
class="btn btn-info btn-sm btn-block"
#click="toiTunesAlbum(result)"
>View on iTunes</button>
</div>
</div>
</a>
</div>
<button class="btn btn-info mt-5 btn-lg btn-block" #click="saveList()">Save</button>
</div>
</template>
<script>
export default {
name: "List",
props: ["List"],
mounted() {
if(localStorage.result) this.result = JSON.parse(this.result);
},
methods: {
saveList() {
localStorage.result = this.result;
localStorage.setItem('result', JSON.stringify(this.result));
/* eslint-disable no-console */
console.log(this.result + 'List Saved');
/* eslint-disable no-console */
},
removeElement: function(index) {
this.List.splice(index, 1);
},
resizeArtworkUrl(result) {
return result.artworkUrl100.replace("100x100", "160x160");
},
toiTunesAlbum(result) {
window.open(result.collectionViewUrl, "_blank");
}
}
};
</script>
<style scoped>
.album-cover {
width: 100%;
height: auto;
background-color: aqua;
}
.album-container {
height: 350px;
}
</style>
Any ideas on how I can save to local storage the rest api result that would be great. Should I be using the List array or result?
I think your problem is that you are only initializing this.result if localStorage.result has a value. If localStorage.result doesn’t have a value the first time you call saveList this.result is still undefined. Try setting a default value or skip trying to save if the value is still undefined. I am also not sure of the relationship between this.List and this.result, since List seems to be a list of results?

Array Splice always delete an item from last?

I am facing a problem in deleting item from an array. Array splice supposed to work but its not working like I want. Its always delete the item from last. I am using Vue.js . I am pushing item dynamically to an array. But after click remove its delete from the last. why I am facing this. I am attaching the codes.
<template>
<div>
<span class="badge badge-pill mb-10 px-10 py-5 btn-add" :class="btnClass" #click="addBtn"><i class="fa fa-plus mr-5"></i>Button</span>
<div class="block-content block-content-full block-content-sm bg-body-light font-size-sm" v-if="buttons.length > 0">
<div v-for="(item, index) in buttons">
<div class="field-button">
<div class="delete_btn"><i #click="remove(index)" class="fa fa-trash-o"></i></div>
<flow-button v-model="item.title" :showLabel="false" className="btn btn-block min-width-125 mb-10 btn-border" mainWrapperClass="mb-0" wrapperClass="pt-0" placeholder="Button Title"></flow-button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import flowButton from '../assets/flow-button'
export default {
name: "textArea",
props:{
index : Number
},
data() {
return {
buttons : [],
btnClass : 'badge-primary',
}
}
components : {
flowButton
},
methods : {
addBtn () {
if(this.buttons.length >= 2) {
this.btnClass = 'btn-secondary'
}
if(this.buttons.length < 3) {
this.buttons.push({
title : ''
});
}
},
remove(index) {
this.buttons.splice(index, 1)
}
}
}
</script>
This must be because of your flow-button I have tried to replicate your error but endup to this code. I just replaced the flow-button with input and it works. Try the code below.
Use v-bind:key="index", When Vue is updating a list of elements rendered with v-for, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of track-by="$index"
You have missing comma between data and components, I remove the component here it won't cause any error now, and more tips don't mixed double quotes with single qoutes.
<template>
<div>
<span class="badge badge-pill mb-10 px-10 py-5 btn-add" :class="btnClass" #click="addBtn"><i class="fa fa-plus mr-5"></i>Button</span>
<div class="block-content block-content-full block-content-sm bg-body-light font-size-sm" v-if="buttons.length > 0">
<div v-for="(item, index) in buttons" v-bind:key="index">
<div class="field-button">
<div class="delete_btn"><i #click="remove(index)" class="fa fa-trash-o">sdfsdff</i></div>
<input type="text" v-model="item.title" :showLabel="false" className="btn btn-block min-width-125 mb-10 btn-border" mainWrapperClass="mb-0" wrapperClass="pt-0" placeholder="Button Title"/>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'textArea',
props: {
index: Number
},
data () {
return {
buttons: [],
btnClass: 'badge-primary'
}
},
methods: {
addBtn () {
if (this.buttons.length >= 2) {
this.btnClass = 'btn-secondary'
}
if (this.buttons.length < 3) {
this.buttons.push({
title: ''
})
}
},
remove (index) {
this.buttons.splice(index, 1)
}
}
}
</script>
I think that you may be facing a conflict with the index prop of your component. Try to use a different name for the index of your v-for loop:
<div v-for="(item, ind) in buttons">
<div class="field-button">
<div class="delete_btn"><i #click="remove(ind)" class="fa fa-trash-o"></i></div>
<flow-button v-model="item.title" :showLabel="false" className="btn btn-block min-width-125 mb-10 btn-border" mainWrapperClass="mb-0" wrapperClass="pt-0" placeholder="Button Title"></flow-button>
</div>
</div>
Try this. Removing an item correctly using this.
<div v-for="(item, ind) in buttons" :key="JSON.stringify(item)">

Categories

Resources