Exploring ways to eliminate an item from a dropdown list within an array using Vue JS

I am currently utilizing an array named 'itemsCart' in my data() and presenting this array within a dropdown list. I have implemented a button to remove items from the array, but I am unsure of how to proceed. Below is my code snippet:

<BreezeDropdownLink2 class=" hover:bg-gray-100 inline-flex w-full py-3 dark:hover:bg-gray-800">
  <div class="justify-between inline-flex w-full">
    <div class="rounded-md bg-gray-100 block h-12 dark:bg-vd2">
      <img src="../Assets/Img/product1.png" class="w-16 h-12">
    </div>
  <div>
  <p class="font-semibold text-gray-500 dark:text-gray-300" v-html="itemsCart[0].title"></p>
  <span class="text-xs mb-10 text-gray-400">By Apple</span>
  </div>
    <div class="inline-flex">
      <NumberInput/>
      <span class="font-semibold text-gray-500 ml-3 mt-5 dark:text-gray-300" v-html="'$'+itemsCart[0].price+'.00'"></span>
      <a @click="" class="dark:text-gray-300"><svg data-v-c52069be="" xmlns="http://www.w3.org/2000/svg" width="14px" height="14px" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="cart-item-remove cursor-pointer feather feather-x"><line data-v-c52069be="" x1="18" y1="6" x2="6" y2="18"></line><line data-v-c52069be="" x1="6" y1="6" x2="18" y2="18"></line></svg>
      </a>
    </div>
  </div>
</BreezeDropdownLink2>
-------------------
<script>
  data(){
    return {
      itemsCart:[
          {
            id: 1,
            title: 'Apple Watch <br> Series 5',
            price: 339.00,
          },
          {
            id: 2,
            title: 'Google - <br>Google Home...',
            price: 129.29,
          },
          {
            id: 3,
            title: 'Apple iPhone<br> 11 (64GB, Black)',
            price: 699.99,
          },
          {
            id: 4,
            title: 'Apple iMac 27-<br>inch',
            price: 999.99,
          },
          {
            id: 5,
            title: 'Apple -<br> MacBook Air...',
            price: 999.99,
          }
        ]
    }
  }
</script>

Note: I understand that I need to create a function to handle the removal process, but I am uncertain about how to go about implementing this function.

Answer №1

Pass the item ID to a method and use the filter function on the itemsCart array:

new Vue({
  el: "#demo",
  data(){
    return {
      itemsCart:[{id: 1, title: 'Apple Watch <br> Series 5', price: 339.00,}, {id: 2, title: 'Google - <br>Google Home...', price: 129.29,}, {id: 3, title: 'Apple iPhone<br> 11 (64GB, Black)', price: 699.99,}, {id: 4, title: 'Apple iMac 27-<br>inch', price: 999.99,}, {id: 5, title: 'Apple -<br> MacBook Air...', price: 999.99,}]
    }
  },
  methods: {
    removeItem(id) {
      this.itemsCart = this.itemsCart.filter(i => i.id !== id)
    }
  },
  computed: {
    itemsCount() {
      return this.itemsCart.length
    }
  }
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<h3>{{ itemsCount }} items</h3>
  <div v-for="(item, i) in itemsCart" :key="i" class=" hover:bg-gray-100 inline-flex w-full py-3 dark:hover:bg-gray-800">
    <div class="justify-between inline-flex w-full">
      <div class="rounded-md bg-gray-100 block h-12 dark:bg-vd2">
        <img src="../Assets/Img/product1.png" class="w-16 h-12">
      </div>
    <div>
    <p class="font-semibold text-gray-500 dark:text-gray-300" v-html="item.title"></p>
    <span class="text-xs mb-10 text-gray-400">By Apple</span>
    </div>
      <div class="inline-flex">
        <!--<NumberInput/>-->
        <span class="font-semibold text-gray-500 ml-3 mt-5 dark:text-gray-300" v-html="'$'+item.price+'.00'"></span>
        <a @click="removeItem(item.id)" class="dark:text-gray-300">
          <svg data-v-c52069be="" xmlns="http://www.w3.org/2000/svg" width="14px" height="14px" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="cart-item-remove cursor-pointer feather feather-x">
            <line data-v-c52069be="" x1="18" y1="6" x2="6" y2="18"></line>
            <line data-v-c52069be="" x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </a>
      </div>
    </div>
  </div>
</div>

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

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Managing multiple URLs in a MEAN Stack application

Currently, I'm working on a MEAN stack project to implement a CRUD system for managing courses. One specific aspect that is giving me trouble is figuring out how to handle unique URLs for each course I create. As of now, I am using routeprovider for t ...

Does the phrase "assigning a closure to a variable" make sense within the realm of JavaScript?

I'm eager to understand the explanation for line 20 in my code example. Line 9 declares a variable named func1. It's set to the closure returned by invoking the function foo(). I understand that calling the function foo() not only returns the ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

The database is failing to reflect any changes even after using the db.insert function

I am currently working on implementing a forgot password feature in my express app using the node mailer package. This functionality involves sending a new password to the user's email and then updating the database with the new password. However, I h ...

jquery toggleClass not retaining previous click event

I came across a show/hide function that seemed promising for my issue, which I found here (credit to the original author). Inspired by this, I created a demonstration on JSFiddle (https://jsfiddle.net/q7sfeju9/). However, when attempting to show rows, it d ...

How can I communicate a message between a content script and a background page in a Chrome extension?

I'm uncertain if my current approach is the most effective for achieving my goal, so any feedback is welcome. My project involves creating a chrome extension that needs to analyze each word on a webpage against a list of 12,000 elements stored in an ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Problem encountered with updating the content data in Handsontable

I'm encountering an issue while trying to implement the handsontable. Specifically, I need to re-render the handsontable based on a dropdown selection. However, despite my efforts, the table does not update correctly after selecting a value from the d ...

Tips for sharing information through a JSON array

"advertisement_types":["ATM","Banner/Poster","Stalls"] Here is the HTML code: input(type='checkbox', value='Mobile/Communication Tower', ng-model='advertisement_types') | Mobile/Communication Tower ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

Consistent assurances kept pouring in, one after the other,

My approach to fetching data from a database using Axios is as follows: Questions Choices Answers I have implemented the code like this: // Get Questions axios.get(url_here) .then(res => { if (res.status === 200) { // Save ...

What is the best way to remove a scrolling event handler from a particular element or class in JavaScript?

My goal is to set up a Table of Contents (TOC) in Obsidian that remains visible as you scroll through the page. Everything functions properly until you reach about halfway down the page, at which point the TOC mysteriously vanishes. #TOC, .TOC { posit ...

Does AngularJS's scope.$apply function operate synchronously?

Can you confirm if this code is synchronous in AngularJS? scope.$apply(function(){ console.log('foo'); }); ...

The Vuetify v-spacer does not seem to be working as intended

When using the <v-dialog> modal, I am attempting to stick one block to the bottom of the <v-col> block by utilizing the <v-spacer> component, but it does not seem to have any effect. What could be causing this issue? You can view an exam ...

When using Next.js revalidate, an error may occur stating: "There are keys that require relocation: revalidate

I have been attempting to utilize the revalidate function in my code by following the example provided by Vercel. However, I keep encountering an error. Here is the snippet of code that I am currently using: export async function getServerSideProps() { c ...

I am looking to update the background color of the material UI helper text

In the image below, you can see that my background color is gray and my text field color is white. When an error is shown, the text field's white color extends and the password error message doesn't look good. I want the text field to remain whit ...

What are some ways to prevent "window.onbeforeunload" from appearing when a form is submitted?

Is there a way to prevent the alert box from appearing when submitting a form using the Submit button below? I want to avoid being prompted to "Leave this page" or "stay on this" after submitting the form. <script> window.onbeforeunload = ...

What is the purpose of adding node_modules to a .gitignore file when you can easily install it from npm anyway?

It appears that excluding the node_modules folder only complicates the process for anyone downloading a project as they will need to execute either npm install or yarn ...

What is causing the Jquery form submit event to not trigger?

I am attempting to use jQuery to submit a form. I need the form submit event to be triggered when jQuery submits the form. However, the submit event handler is not being called successfully after the form is submitted. Here is the code snippet: <html ...