Unable to delete component from an array (slice, Vue.js)

I'm currently working on implementing dynamic addition and removal of components in Vue.js.

I've encountered an issue with the slice method, which is supposed to remove an element from an array by the provided index. To modify the array, I am using slice(i,1).

According to an answer found here, this method should work for me, but unfortunately, it's not functioning as expected.

What am I doing incorrectly?

Below is the code snippet along with a link to a corresponding CodePen:

<div id="app">
  <button @click="addNewComp">add new component</button>
  <template v-for="(comp,index) in arr">
    <component 
     :is="comp"
     :index="index"
     @remove-comp="removeComp(index)"
     ></component>
  </template>
</div>
<script type="text/x-template " id="compTemplate"> 
  <h1> I am a component {{index}} 
  <button v-on:click="$emit('remove-comp')">X</button>
  </h1>
</script>

 const newComp = Vue.component("newComp",{
  template:"#compTemplate",
  props:['index']
})

new Vue({
  el:"#app",
  data:{
    arr:[newComp]
  },
  methods:{
    addNewComp:function(){
      this.arr.push(newComp);
        console.log(this.arr);
    },
    removeComp:function(i){
      console.log(i);
       this.arr.slice(i,1);
       console.log(this.arr);
    }
  }
})

Answer №1

 const newComponent = Vue.component("newComponent",{
  template:"#compTemplate",
  props:['index']
})

new Vue({
  el:"#app",
  data:{
    components:[newComponent]
  },
  methods:{
    addNewComponent:function(){
      this.components.push(newComponent);
    },
    removeComponent:function(i, a){
      console.log('i', i, a, typeof i);
      this.components.splice(i,1);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
  <button @click="addNewComponent">add new component</button>
  <template  v-for="(comp,index) in components">
    <component 
     :is="comp"
     :index="index"
     @remove-comp="removeComponent(index, 100+index)"
      :key="`${index}`"
     ></component>
  </template>
</div>
<script type="text/x-template " id="compTemplate"> 
  <h1> I am a component {{index}} 
  <button v-on:click="$emit('remove-comp')">X</button>
  </h1>
</script>

I came across this information which relates to Vue and how it handles reactive states. .slice() is considered non-reactive as it creates a copy without changing the original data. It is recommended to use .splice() which is reactive, or explore the usage of .filter() here

Answer №2

tag, you have been using the slice method instead of the splice method referenced in the shared link. Here is the corrected code snippet:
deleteEvent: function(index) {
  this.events.splice(index, 1);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When you attempt to "add website to homescreen" on an iPhone, Ajax malfunctions

I have a unique website feature that utilizes ajax to dynamically load content when the user interacts with certain buttons. Everything functions smoothly up until a user tries to access the website through the "add to homescreen" option on mobile Safari a ...

Determining the percentage between two elements using Bootstrap 4's range slider

I've been searching everywhere but haven't found a solution. I am trying to implement Bootstrap 4.5's range slider to distribute the % difference between Client and Company, ranging from 1% to 100%. However, I am struggling with the jquery/j ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...

Understanding Angular's transclusion functionality and how it interacts with scopes

I've been working on creating a directive for click-to-edit input fields. My goal was to make it an attribute type directive that can work with various types of input fields by simply transcluding the input field itself. However, I've encountere ...

Protecting an API with passport-local authentication

Let me get right to the point. I've developed a secure application using passport-local, with all routes well-covered. The purpose of my app is to retrieve data from MongoDB and serve it as an API that feeds into d3 charts. While all my webpages are s ...

Is getElementById() returning null?

I'm currently working on a JavaScript program that takes an image URL and displays it on the page by creating an <img> tag. This way, I can easily add multiple images to the page. Here is my code: <!DOCTYPE html> <html lang="en&quo ...

I am experiencing an issue where the button I place inside a material-ui table is unresponsive to clicks

Here is the structure of my table: <TableContainer component={Paper} style={{height: "40vh", width: "90vh"}}> <Table size="small" sx={{ minWidth: 200 }}> <TableHea ...

Removing an item from an array using AngularJS with Underscore or another method

Although my question may seem similar to others, it is unique! Please review to understand my specific situation. I am dealing with an array of objects that looks like this $scope.events =[ { $$hashKey: "009" _allDay:false _i ...

Looking for guidance on integrating REST API consumption features into Ionic Framework 3.x?

It's been a long time since I last used the ionic framework. The version I worked with was 1, where every page created with Ionic Creator had its own controller for adding JavaScript code to consume my REST framework. Now that I've downloaded th ...

Tricking Vuejs into triggering a @change event

I possess the following: <input type="radio" :name="activity" v-model="activity" :value="1" v-on:change="callProc(data, data2)" required> Ho ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...

What is the best way to retrieve web pages from the cache and automatically fill in form data when navigating to them from different pages on my website?

On my website, I have multiple pages featuring forms along with breadcrumbs navigation and main navigation. Interestingly enough, the main navigation and breadcrumbs share some similarities. However, my desire is that when users click on breadcrumb links, ...

Creating a mask for both integer and decimal values in jQuery

I have created a validation mask in my code to verify user input when onBlur unitprmask:/^\d+,\d{1,1}$/, However, the current mask only allows for decimal numbers, requiring at least one decimal place. I want users to be able to enter whole in ...

Retrieve the data of elements that have been clicked using jQuery

I am struggling with a particular issue and would appreciate some assistance. Recently, I've been working on developing buttons that, when clicked, add data to a form for submission. An example of the code structure is as follows: <div> < ...

Utilizing an Office App Ajax that includes an authentication header, the application connects to a secure Web API 2 backend with CORS

I am currently in the process of developing a content panel application for Office. As part of this project, I need to authenticate an account against a server. To accomplish this, I have implemented my own AuthorizationFilterAttribute on my web api 2 con ...

Error message indicating that the event "OnkeyDown" is not in sync within the React application

Hey everyone! I'm a beginner in web development and I'm struggling to understand why the event "OnKeyDown" is triggered the second time. My task involves changing (increasing, decreasing) parts of a date (day, month, year, hour, minutes, seconds) ...

"Troubleshooting: jQuery Find function not functioning correctly with HTML template

I am having trouble with a Shopify liquid code that I am trying to load into an HTML template <script type="text/template" id="description"> <div class="product-ddd"> {{ product.description }} </div> ...

Utilizing JavaScript to trigger the :hover pseudo-class and implement event transfers

Consider this situation: You have a scenario where two images are stacked on top of each other. The image with the highest z-index is transparent and handles click events, similar to Google's Map API, while the image below is for visual representatio ...

Checking for mobile SSR in a ReactJS applicationUncover the signs of mobile

I recently integrated the mobile-detect library into my project following this informative tutorial: link /src/utiles/isMobile.tsx: import MobileDetect from "mobile-detect"; import { GetServerSidePropsContext } from "next"; export co ...