Creating a seamless integration of elements from two Vue.js components

As I work on developing the checkout page for an e-commerce app, I encounter the need to display a list of OrderItems from the database, each with its price and quantity. These items can be selected and grouped together. Additionally, I must also include a separate list of "addons" for the basket, which are also OrderItems but of a different type.

To accomplish this, I have implemented a Vue.js component that renders an array of OrderItems for selection. My initial approach involves rendering the same component twice. However, the "selected" property currently only supports models from one list or the other, but not both simultaneously. I aim to enhance the functionality so that the selected prop can contain items from both lists (basic OrderItems and addons).

For the code and a live demo, please refer to the following links:

JS Fiddle: https://jsfiddle.net/w8vfb64L/

Template:

<!-- Template code goes here -->

Javascript:

var implementationDetails = new Vue();

var customComponent = Vue.component('custom-component', {
  template: '#custom-template',
  props: {
    entries: [Array, Object],
    selected: Array,
    addons: Array,
    frequencies: [Array, Object],
  },
  created: function() {
    this.entriesCopy = this.entries;
    this.selectedCopy = this.selected;
  },
  watch: {
    selectedCopy: function(val, oldVal) {
      implementationDetails.$emit('selected-updated', val);
    }
  },
  data: function() {
    return {
      entriesCopy: [],
      selectedCopy: [] 
    }
  }
});

new Vue({
  el: '#app',
  data: {
    // data properties here
  },
  components: {
    'customComponent': customComponent,
  },
  created: function() {
    var temp = this;
    implementationDetails.$on('selected-updated', function(selected) {
      Vue.set(temp, 'selected', selected);
    });
  },
  computed: {
    // computed properties here
  }
});

Answer №1

I had to make significant changes to the codebase in order to adhere to your desired cart-building structure. It was necessary to rethink the data structuring aspect to achieve this:

For reference, here's the updated fiddle: https://jsfiddle.net/thebigsurf/w8vfb64L/11/

EDIT

In order to allow for the updating of multiple fields within the product object, it seems that using v-model may no longer be suitable. As an alternative, instead of assigning a v-model to the component directly, you can pass it a method that enables updating any of the item's fields:

Updated fiddle with the proposed solution: https://jsfiddle.net/thebigsurf/0chtzwjd/2/

...

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

Using JQuery to find the nearest element and narrowing down the search to its child elements

In my program, I have 3 forms identified by form1, form2, and form3. Each form contains its own set of dropdown lists named drop1 and drop2, along with a submit button. When the submit button is clicked in any form, it checks which option was selected from ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

Under what circumstances is it possible to iterate through an empty array?

When defining arrays in JavaScript using Array(n), it creates an empty array. If I write the following code: Array(2).map((val) => console.log(val)) Nothing happens when running this code, but if I spread out the elements of the array into another a ...

Tips for choosing or moving to an iframe

What is the best method for choosing or transitioning to an Iframe (as the currently targeted document) using Selenium webdriver in Firefox? Are there alternative approaches for selecting an iframe with or without webdriver? driver.switchTo.frame("Frame ...

Do not ask for confirmation when reloading the page with onbeforeunload

I am setting up an event listener for the onbeforeunload attribute to show a confirmation message when a user attempts to exit the page. The issue is that I do not want this confirmation message to appear when the user tries to refresh the page. Is there ...

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

Set up a WhatsApp web bot on the Heroku platform

I am currently in the process of developing a WhatsApp bot using the node library whatsapp-web.js. Once I finish writing the script, it appears something like this (I have provided an overview of the original script) - index.js const {Client, LocalAuth, M ...

Is it possible to add my own designs to a three.js model?

I am looking to add some personal touches to my three.js model by drawing on it in the scene. How can I achieve this effect of 'graffiti' on my models within the scene? ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Attempting to execute a code snippet using Express framework on the local server at port 3000

Having some trouble with my initial attempt at a basic application. The Scraper.js file successfully scrapes a URL and outputs the array to the document object when executed in the console. Now, I want to set up an Express server to run the script whenever ...

Ways to link a Javascript or Jquery function to an HTML form

I am looking to develop a form that can extract email addresses from input text. While I know there are many scripts available that can do this quite easily, my goal is to create one on my own. After reading, researching, and experimenting with differ ...

Interacting with my Rails API through JavaScript requests

Exploring the world of Rails and diving into creating a basic rails-api. Currently facing an issue while trying to incorporate user addition to my model using a JavaScript request... Let's take a look at my HTML file named add-user.html: <script ...

I'm experiencing a problem with my React application where errors are not being shown in the browser. Instead

https://i.sstatic.net/FTMz7.png Why is React only displaying an empty screen instead of showing errors like on my instructor's system? https://i.sstatic.net/QCbgG.png How can I resolve this issue? EDIT: While I can see the error in the console and ...

The MuiThemeProvider.render() function requires a valid React element to be returned, or null if necessary

I am working on creating a dropdown using Material UI and React. It renders perfectly when the dropdown component is in my src/app.js, but I encounter errors when I move it to a separate file named fruits.js: MuiThemeProvider.render(): A valid React el ...

NodeJS - Retrieving files from Google Drive

Here is a code snippet that I'm using to download files from Google Drive: function downloadDrive(fileId, callback) { var fileExt = fileId.split("."); var file = Date.now() + "." + fileExt[fileExt.length - 1]; var dest = fs.createWriteStream(". ...

Enabling auto-expansion for textareas with every keystroke

Currently, I have implemented the following script: jQuery.each(jQuery('textarea[data-autoresize]'), function() { var offset = this.offsetHeight - this.clientHeight; var resizeTextarea = function(el) { jQuery(el).css('h ...

Updating HTML images in real-time using a combination of Flask and Ajax

I am facing a situation similar to the one discussed in this thread: Flask+AJAX+Jquery+JINJA to dynamically update HTML Table. However, I am struggling to adapt the solution to suit my specific requirements. My objective is to automatically update the imag ...

Master the art of zeroing in on your drawing once it's complete

Please review the Demo and provide instructions on how to enhance the zoom function for Google Maps after the map is drawn. let map; let drawingManager; $(document).ready(function () { const latlng = new google.maps.LatLng(49.241943, -122.889318); ...

Pass PHP array to a JavaScript file using AJAX

Starting with a basic knowledge of PHP and AJAX, I was tasked with creating a form that prompts the user to choose between two car manufacturers. Upon selection, the form should display all models of the chosen make from a multidimensional array stored in ...

switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here. Is there a simpler way to achieve this? I currently have to create two clas ...