Merging a prop of array type in a Vue component


I'm encountering an issue in my component where using the splice function on an array prop does not trigger the $emit event. Can anyone provide some insight into why this might be happening? The removeItem method is called by clicking a button.

View Code

Thank you 🤚

Answer â„–1

Using the splice method does not trigger the set function on a computed property. To work around this, simply assign the computed property to itself after using the splice method.

this.customBenefitsObj = this.customBenefitsObj;

To illustrate this behavior, refer to the demo below where "Test" is only logged once.

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  computed: {
    test: {
      get() {
        return [1, 2, 3, 4, 5];
      },
      set(v) {
        console.log("Test");
      }
    }

  },
  mounted() {
    this.test.splice(0, 1);
    this.test = this.test;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Answer â„–2

When you use the splice method, it alters the content of customBenefitsObj, but not the array itself. For example:

this.customBenefitsObj = []

In this case, the set function of customBenefitsObj will be triggered, along with the emit function.

It is generally advised against mutating props directly. Instead, you should emit a modified copy of the array and replace it in a parent component. Alternatively, you can emit a remove operation along with the element to be removed (the actual removal process should ideally take place in the parent component).

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

Finding the name of a particular item in an array and increasing its value - a step-by-step guide

For a homework project, I am developing a straightforward cart system. Could someone advise me on the best approach to retrieve an item from an array and increment its value by one? The array contains 25 items, each with a unique name but without any IDs a ...

Eliminate the ripple effect from the icon button

I am looking to create an icon that will perform the button's task of loading, while also removing the rounded button effect from this icon. Is there a way to achieve this? Visit this link for more details. <div id="app"> <v-app id="inspi ...

Having trouble accessing the Ajax "data" parameter in Twisted

An ajax request is made using the "POST" method with these parameters: function sendDataToServer(portNumber){ console.log(portNumber) $.ajax({url: "action", dataType : 'html', type: "POST", data: portN ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Guide on transferring a 200MB database to an HTML5 web page executed locally

In the process of creating a search tool for internal use within my organization, I have established a deployment strategy that involves: Storing an HTML5 web page on the file server. Keeping a 200MB JSON or JavaScript file in another location. Currentl ...

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

Issues with React and Recharts legend functionality causing disruptions

I am currently experimenting with React and Recharts to build a stacked and grouped bar chart. This is my first experience using Recharts, and I have encountered an issue with the legend functionality. I would like the legend to toggle both graphs within e ...

Choose a specific date on a Materialize datepicker and set it as the selected date

I am currently developing an application using Materialize that includes two datepickers: $(document).ready(function(){ $('#outDate').datepicker({ format: 'dd-mm-yyyy' }); }); $(document).ready(function(){ $(&apos ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Retrieve the user-inputted data from an Electron BrowserView's input field

Consider this scenario where a BrowserWindow is set up with specific security settings, including enabling the webviewTag: true for project requirements. let webPrefs = { plugins: false, nodeIntegration: false, nodeIntegrationInWorker: false, ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

What alternative methods are available to rename a field that has been returned in mongoose, if at all possible?

I need help with this specific query: MessageModel.find({ conversationId: { $in: ids } }) .sort({createdAt: 'ascending'}) .populate({ path: 'receiver', select: '_id' }) .populate({ path: &a ...

Try utilizing the Array.map method with a two-dimensional array

My current challenge involves a 2-dimensional Array where I am attempting to implement a "randomBool" function on each of the elements within it. The "randomBool" function essentially generates a random boolean value: const randomBool = () => Boolean( ...

vuejs props become null upon page refresh

MyComponent.vue template: <ResponsiveNavigation :nav-links="navLinks" /> script data: () => ({ navLinks: [] }), created: function() { this.getSocialMediaLinks(); }, methods: { getSocialMediaLinks() { var self = this; ...

The Hyperledger Sawtooth JavaScript SDK has encountered invalid submitted batches

I am currently working on integrating a hyperledger sawtooth transaction using the javascript SDK. I am following the tutorial provided here: . /* *Create the transaction header */ const createTransactionHeader = function createTransactionHeader(payloadBy ...

Particles are not appearing when using the Three.js shader material

Hey there, I've been working on a simple scene with a grid of particles in the shape of a cube. Check it out here: https://codepen.io/sungaila/pen/qqVXKM The issue I'm facing is that when using a ShaderMaterial, the particles don't seem to ...

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

Guide to forming a JavaScript array from nested JSON data

Looking to parse through an array of objects related to London weather data from the OpenWeatherMap API. How can I create three distinct arrays in JavaScript, each with variable names "dtArray", "tempMinArray", and "tempMaxArray", containing only values f ...