What is the best way to bring JavaScript code from one component to another in React?

I am currently working on a mini shop app using VueJS without a backend, focusing on adding items to the shopping cart only.

Within Component One (Nmdgrey.vue), I have boots along with an "Add to Cart" button.

<button @click="addToCart">Add to cart</button>

The function in the first component looks like this:

methods: {
  addToCart() {
    const boots = { name: 'adidas nmd' };
    this.cart.push(boots);
  }
} 

Additionally, I have Component Two which displays the shopping cart.

<div v-for="item in cart">
  {{item.name}}
</div>

In JavaScript:

import Nmdgrey from '@/components/Nmdgrey.vue';
export default {
  name: 'Shoppingcart',
  components: 
    Nmdgrey,
  data() {
    return {
      cart: [
        { name: 'adidas adizero' },
      ]
    }
  },
 };

How can I add boots from Component One to the list in Component Two?

Even though I used this.cart.push(boots); in Component One, it didn't work as expected.

Here is what I want, but unfortunately, the button doesn't work: codesandbox

Answer №1

Utilize $emit to enable communication from child components to parent components.

For more information, please see the official documentation: Listening-to-Child-Components-Events

Nmdgrey.vue

<template>
  <div>
    <!-- component 1 -->
    <button @click="add">Add to cart</button>
  </div>
</template>

<script>
export default {
  name: "Numdgrey",
  methods: {
    add() {
      const boots = { name: "adidas nmd" };
      this.$emit("add", boots);
    }
  }
};
</script>

Shoppingcart.vue

<template>
  <div>
    <!-- component 2 -->
    <nmdgrey @add="addCart"></nmdgrey>
    <br>
    <div v-for="(item, index) in cart" :key="index">{{item.name}}</div>
  </div>
</template>

<script>
import Nmdgrey from "./Nmdgrey.vue";
export default {
  name: "ShoppingCart",
  components: {
    Nmdgrey
  },
  data() {
    return {
      cart: [{ name: "adidas adizero" }]
    };
  },
  methods: {
    addCart(good) {
      this.cart.push(good);
    }
  }
};
</script>

Codesandbox demo : https://codesandbox.io/s/z2qz6oy8yp

Answer №2

Based on your question, it seems like you are interested in sharing data between multiple Vue components. One solution for this is to implement Vuex, a tool that offers centralized state management.

By utilizing Vuex, you can create mutations to add items to a cart that can be accessed by any component. Additionally, you can retrieve cart data from any component using Vuex getters.

Answer №3

In order to successfully transfer all necessary data from one page to another and proceed with the process of adding items to the cart, you must implement a post method. This method will enable you to seamlessly transition between pages and complete the creation of your desired page.

Answer №4

Check out the live demo on CodeSandbox: https://codesandbox.io/s/94l44j8j14

Incorporate the use of `props` to transmit values to the cart component.

View Nmdgrey.vue below:

<template>
<div>
  <b>Component 1 : NmdGrey</b><br><br>
<button v-for="(product, index) in boots" :key="index"
@click="addToCart(product.name)" >Add {{product.name}} to Cart</button>
<br><br><hr><br> 
  <shoppingcart :cart="cart" />
  </div>
</template>

<script>
import shoppingcart from './shoppingcart.vue';
export default {
name: 'Nmdgrey',
components:{shoppingcart},
data() {
    return {
      boots:[{name: 'adidas adizero'}, {name: 'puma walker'}, {name: 'nike shoe'}, {name: 'adidas plain'}],
      cart:[],
    }
  },
  methods: {
addToCart(boots) {
  this.cart.push({ name: boots });

  }
} 

}
</script>

Refer to Shoppingcart.vue code snippet below:

<template>
  <div>
    <b>Component 2 : Shopping cart</b>
    <br>
    <br>
    <div v-for="(product, index) in cart" :key="index">{{product.name}}</div>
  </div>
</template>

<script>
export default {
  name: "Shoppingcart",
  props: ["cart"],
  data() {
    return {};
  }
};
</script>

Answer №5

If your application is on the smaller side, consider utilizing Vue mixins to create a reusable function like addToCart that can be easily called within your components.

Just like methods, mixins can help you share data across different components in your application.

For more information on how to use mixins in Vue, check out the official documentation here.

Check out this JsFiddle link for a working example: JsFiddle

I hope this explanation proves helpful!

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

How to retrieve URL parameters from within the when() function in AngularJS

Consider the code snippet below: $routeProvider.when('/movies/:type', { title: 'Movies', templateUrl: 'pages/movies/movies.html', controller: 'MoviesCtrl' }); Is there a way to retriev ...

What is the inner workings behind server side rendering in Next.js?

I am seeking clarification on Server Side Rendering, specifically with Next.js. During server side rendering, I want to confirm the 'execution path' as follows: Client makes a request to the server for the webpage, which serves up an HTML only ...

Why does the HTML and CSS slider fail to load upon page refresh, yet works perfectly when the next or previous button is clicked?

There seems to be an issue with the slider images not loading on page refresh. Oddly enough, they appear only after clicking the next button. However, upon refreshing the page again, the images disappear. <div class="slide-banner"> < ...

Using data variables as arguments in the style section of Vue2

Suppose we have a data variable and I want to utilize this data variable for styling purposes. data() { return{ selected:{ index: 2 } } } <style> .parent-table >>> .table-row:nth-child(/* here I intend to use ...

The issue of double submission persists, with the prevention of the default action

I'm in need of assistance. Within my form, I have two buttons displayed on the page: "Save" and "Publish". Below is the corresponding HTML code: <button type="submit" class="button">Save</button> <button type="button" class="button" n ...

Having trouble with your Jquery resize or scroll function?

function adjustNavbar() { if ($(window).width() > 639) { $(document).scroll(function () { if ($(window).scrollTop() > 60) { $('.navbar').addClass('background', 250); } else { ...

Pass a reply from a function to a route in expressjs

I'm currently working on a project where I need to retrieve JSON data from an API using an Express server in Node.js. However, I'm facing some confusion regarding how Node.js manages this process. In my code, I have both a function and a route de ...

Navigating with Angular 1.5 Component router in conjunction with Express.js

I'm currently working on an Express application and I am trying to capture all routes to redirect users to /public/app/index.html: app.all('/*', function (req, res, next) { // Let's just serve the index.html for other files to enab ...

Transforming Ember's ajax query string

Using ember-model, I am making a request like this: App.Video.find({'sort':'createdAt+asc'}); to retrieve a sorted list of videos. This should result in the following request: http://localhost:1337/api/v1/videos?sort=createdAt+asc How ...

Trouble arises when attempting to add an image to a spherical object

I've searched through various threads, Googled extensively, watched YouTube tutorials.... But I can't seem to figure out how to apply a texture to my Sphere. When I run this code, all I see is a white Sphere without any texture showing up. Can so ...

Use jQuery to swap out images and witness the image loading in real time

Currently, I am using jQuery to dynamically change images by using the code $('img').attr('src','newUrl'); However, whenever I do this, the image is only displayed once it has completely loaded. Due to my slow internet conne ...

Troubleshooting a scenario where making edits to a mongoDB item does not result in any updates

I am struggling with a problem in my nodeJS application involving updating items in a mongoDB database. I have successfully implemented features to add and remove notes, but when attempting to update a note, the changes do not reflect in the database. Desp ...

The function fs.createReadStream does not exist

Snippet to Submit Career Form: import axios from 'axios'; import FormData from 'form-data'; var fs = require('fs'); submitCareerForm(e){ e.preventDefault(); let formData = new FormData(); //formdata obje ...

Unable to display the string following a space in the value attribute of an hbs file

<input type="text" class="form-control" id="exampleInputEmail2" name="productName" value={{product.productName}} > When I input 'Smart Phones' into product.produc ...

Could anyone provide some insight into the reason behind this occurrence?

I just came across the most peculiar situation I've ever experienced. Check out this unique test page: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> fun ...

Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data. ngOnInit() { this.getProgress(); } getFirstProgramItem() { this._contentfulService.getProgramItem(4, 1) .then((programItem) = ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

How to access data from a child component in a Vue 3 template

Within my project, there are three Vue components that utilize the Composite API with the setup option. My goal is to access data within a nested tree structure. The code below provides a simplified version of what I am trying to achieve. The application ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...