Pass the specific index of an object located outside of a v-for loop in Vue 3

For educational purposes, I am working on building a basic shopping cart using Vue 3.

So far, I have successfully set up the products object and implemented the addToCart() functionality. Everything is functioning smoothly within a v-for loop.

However, the challenge arises when I attempt to display the title of the product in an alert outside the v-for loop. I am unsure of how to achieve this in Vue.

I have experimented with emit and provide, but so far they have not yielded the desired results. While using provide allows me to send the entire object to the child component Alert.vue, it does not solve my specific need, which is to retrieve the current index of the selected product in order to fetch its title.

You can view a demo of the project here.

To see the issue firsthand, try adding a product to the cart twice and observe the Alert message. Currently, it displays the entire cart object instead of just stating "

You have already added {product.title} to your cart
" as intended.

Here's a snippet of the code:

export default {
    name: 'App',
    components: {
        CartAlert
    },
    data() {
        return {
            products: [
                {id: 1, title: 'Samsung A70', price: 50},
                {id: 2, title: 'Kindle Reader', price: 50},
                {id: 3, title: 'Meta Quest 2', price: 100},
                {id: 4, title: 'LG LED 43" TV', price: 200},
            ],
            discountInput: '',
            discountValid: false,
            cart: [],
            total: '',
            alreadyAddedToCart: false
        }
    },
    methods: {
        addToCart(index) {
            if (this.cart.includes(this.products[index])) {
                this.alreadyAddedToCart = true
            } else {
                this.cart.push(this.products[index])
            }
        },
    },
    provide() {
        return {
            cart: this.cart
        }
    }
}

In the Alert.vue component (child component), the code looks like this:

<template>
    <div id="alert" class="alert alert-danger alert-dismissible fade show" role="alert">
        You have already added this {{ cart }} to your cart.
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"
                @click="$emit('dismissAlert')"></button>
    </div>
</template>

<script>
export default {
    name: "CartAlert",
    props: ['product'],
    inject: ['cart'],
    mounted() {
        console.log()
    }
}
</script>

Answer №1

To display your prop product in the Cart component:

The item {{ product }} has already been added to your cart.

In your app, add the item to the data function:

item: null

Within the method, assign a title to this data property:

this.item = this.products[index].title;
this.alreadyAddedToCart = true;

In the template, bind your property to the item:

:product="item"

Check out this demo for reference.

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

Separate angular structure into various sections

I am developing a form builder using Angular dynamic form functionality. The form data is loaded from a JSON object, as shown below: jsonData: any = [ { "elementType": "textbox", "class": "col-12 col-md-4 col-sm-12", "key": "first_ ...

Embed the Three.js CSS3DRenderer scene within a designated div element

I am interested in using the Three.js CSS3DRenderer to create a three-dimensional composition. Here is the code I have: "use strict"; var OrbitControls = THREE.OrbitControls, CSS3DRenderer = THREE.CSS3DRenderer, CSS3DObject = THREE.CSS3DObject, S ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Changing the color of the placeholder in the Vuetify select component

I've been attempting to modify the placeholder text color of a Vuetify select box. Here is what I tried: <v-select :items="items" placeholder="place" dense> </v-select> .v-text-field--placeholder { color: gr ...

Error in the code that I am unable to locate in JavaScript, HTML, and CSS

I need help creating a navbar that displays the active site using HTML and JS code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content=& ...

The UI Router template fails to inject despite state changes occurring

I've been attempting to create nested views, you can check out the Plunker demo https://embed.plnkr.co/oRMnMW4QoWwhSkm9maHf/. The state is updating as expected but the template remains the same. Could someone please point out where I may have gone wr ...

Notify the user with a Jqgrid alert when they attempt to select multiple checkboxes

When editing rows, I wanted to avoid multiple selections. In order to achieve this, I need to check the condition if(count>1) and display an alert message. I am struggling to figure out how to retrieve the count of selected checkboxes in jqGrid. var m ...

Error encountered: _moment2.default.date is not a recognized function within the React application

I keep encountering an issue when attempting to utilize a date from Moment.js in the constructor, componentWillMount, or componentDidMount. The error message I receive is: Uncaught TypeError: _moment2.default.date is not a function It's worth noting ...

The integration between Laravel and Vue.js seems to be causing issues with locating the CSS and JS files

I am currently working on a Laravel + Vue.js project that I need to enhance. Unfortunately, I cannot share the code due to NDA restrictions. The project consists of an API in Laravel and a front end in Laravel using Vue. After committing the project, updat ...

Tips for arranging elements vertically in HTML

Recently, I created a code that triggers a function when a button is clicked. This function moves one div above another when the Up button is clicked, and vice versa for the Down button. Do you have any ideas on how to achieve this? http://jsfiddle.net/W ...

Eliminate Bootstrap's validation glyphs

Issue Description I am attempting to eliminate the validation icons from Bootstrap, such as the "x" and "check" symbols. Despite my efforts to search thoroughly, I have been unable to locate where these icons are located in the code. Code Sample You can ...

Ways to showcase contents inside a specific div when hovering with a mouse

I am working with a div structure that includes menus and items within each menu. <div id="navigate"> <div class="menu"> <div class="group">Mail</div> <div class="item">Folders</div> <div clas ...

what is the mechanism behind __dirname in Node.js?

Node.js is a new technology for me and I recently discovered the "__dirname" feature which is really useful for obtaining the absolute path of the script. However, I am intrigued by how it works and how it manages to interpret the directory structure. De ...

Deactivate text/input field in React and Next.js based on Dropdown Selection

As a newcomer to React, I am facing an issue with disabling and enabling an input field based on the selected value in a dropdown. My tech stack includes React, Next Js, React-bootstrap, and formik. function Input(){ const [disabled, setDisabled] = useStat ...

Verify that the first textbox contains a value before setting the second textbox to be mandatory

There are three textboxes in my form. <asp:textbox id="txt1" runat=server> <asp:textbox id="txt2" runat=server> <asp:textbox id="txt1" runat=server> <asp:button ID="btnCheck" text="check" runat=server onclick="btnCheck_Click"> I n ...

Obtain the RadNumericTextBox value using JavaScript or jQuery in an ASP.NET environment

In my ASP.Net Web Page, I have a RadNumericTextBox within a DetailsView. I am attempting to access this element in JavaScript using jQuery. Despite successfully obtaining the RadNumericTextBox as a variable in JavaScript and verifying that it contains all ...

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

How to retrieve a property with a colon in JavaScript object

After parsing XML into JSON with xml2js, I found elements with colons like this: obj = { "data:example":"smthing"}; Is there a way to directly access these elements in JSON? Any tips or tricks? Thank you! ...

Is it possible to reorganize the JavaScript modules created by the TypeScript compiler?

In my TypeScript project, the structure resembles that of a typical Maven Java project. Here is an overview of how the project is organized: *.js file for commonjs/webpack, system, and amd.</p> For commonjs/webpack, I utilize tsc with tsconfig.jso ...

Extracting data from a JSON array using JavaScript: A guide

I'm encountering an issue with a PHP function that returns an array to JavaScript. Here's how the code looks: $data['first'] = 10; $data['second'] = 20; echo json_encode($data); Upon receiving the value in JavaS ...