Generate a Vue Component in real-time with a click of a button

My task involves populating a list of orders using the orders array. Each order has an edit functionality that triggers a vuetify dialog box component when clicked, displaying default data for editing. Here's my current approach:

<tbody class="items">
  <tr v-for="order in orders" :key="order.name">
    <td>{{ order.fullname }}</td>
    <td>{{ order.address }}</td>
    <td>{{ order.phone }}</td>
    <!-- <td>{{ order.orderQuantity }}</td> -->
    <td>{{ order.quantity }}</td>
    <td v-if="order.status == true">
      <v-chip small outlined class="ma-2 chip" color="green">delivered</v-chip>
    </td>
    <td v-if="order.status == false">
      <v-chip small outlined class="ma-2 chip" color="red">in progress</v-chip>
    </td>
    <td>
      <v-dialog v-model="dialog" persistent max-width="290">
        <template #activator="{ on, attrs }">
          <v-btn icon color="primary" dark v-bind="attrs" v-on="on"> Open Dialog </v-btn>
        </template>
        <v-card>
          <v-card-title class="headline"> Use Google's location service? </v-card-title>
          <v-card-text>{{ phone }}</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="green darken-1" text @click="dialog = false"> Disagree </v-btn>
            <v-btn color="green darken-1" text @click="dialog = false"> Agree </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </td>
  </tr>
</tbody>

However, I'm facing an issue where multiple instances of the dialog box are generated prematurely. I attempted to use async components but couldn't identify the mistake.

My desired outcome is to automatically display and remove a dialog box with default order details when the "edit order" button is clicked. Any corrections or suggestions would be appreciated.

Answer №1

  1. Separate the dialog part into its own component
  2. In the parent component, include it once at the start with dialog=false to initially hide it
  3. Introduce a data attribute called orderToEdit that will serve as a prop for the child component
  4. Add an edit button for each order in the list that will trigger a method upon clicking and pass the corresponding order
  5. Within this method, update orderToEdit with the selected order from the clicked item and set dialog=true to display it with custom values

const dialogmodel = Vue.component('btn', {
  template: '#dialogmodel',
  props: { order: Object, value: Boolean },
  computed: {
    dialog: {
      get () { return this.value; },
      set (value) { this.$emit('close', value); }
    }
  }
});

new Vue({
  el:"#app",
  vuetify: new Vuetify(),
  components: { dialogmodel },
  data: () => ({
    orders: [
      { name:"1", fullname:"fullname1", address:"address1", phone:"phone1", quantity:"quantity1", status:false },
      { name:"2", fullname:"fullname2", address:"address2", phone:"phone2", quantity:"quantity2", status:true }
    ],
    dialog:false,
    orderToEdit: {}
  }),
  methods: {
    closeDialog(value) { this.dialog = value; },
    editOrder(order) { this.orderToEdit = order; this.dialog = true; }
  }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bec8cbdbfe8c90c6">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98f8c9c8d909f80b9cbd781">[email protected]</a>/dist/vuetify.js"></script><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d6b6263794d392375">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e181b0b1a0708172e5c4016">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">

<template id="dialogmodel">
  <div>
    <v-dialog v-model="dialog" max-width="290" persistent>
      <v-card>
        <v-card-title class="headline">
          {{ order.fullname }}
        </v-card-title>
        <v-card-text> {{ order.address }} </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="green darken-1" text @click="$emit('close')">
            Disagree
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<v-app id="app">
  <div>
    <dialogmodel v-model="dialog" :order="orderToEdit" @close="closeDialog" />
  </div>
  <div>
    <table>
      <tbody class="items">
        <tr v-for="order in orders" :key="order.name">
          <td>{{ order.fullname }}</td>
          <td>{{ order.address }}</td>
          <td>{{ order.phone }}</td>
          <td>{{ order.quantity }}</td>
          <td v-if="order.status == true">
            <v-chip small outlined class="ma-2 chip" color="green">delivered</v-chip>
          </td>
          <td v-if="order.status == false">
            <v-chip small outlined class="ma-2 chip" color="red">in progress</v-chip>
          </td>
          <td>
            <v-btn @click="editOrder(order)">Edit</v-btn>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</v-app>

Answer №2

Would you like a central popup that displays the details of the order you want to edit? If so, instead of adding multiple components to your v-for loop, you can streamline by creating a single component for the edit popup.

Here's how you can do it:

  1. Click on 'edit' and set a data property called 'orderIndexToEdit' to the index of the order in the v-for loop
  2. Show a single dialog box when 'orderIndexToEdit' is true using v-if or v-show
  3. Create a computed property that retrieves the correct order from the orders array based on the index stored in 'orderIndexToEdit'
  4. Use this computed property to fill in the details of the dialog box

Let me know if this solution works for you!

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

Storing various text inputs in a MySQL database

Could anyone please assist me with fixing an issue I'm having with inserting data into a database from the form provided below? Unfortunately, I am unable to get it to work as expected. Here is the complete form: <html> <head> <m ...

The browser's window.location.href fails to redirect the page

Here are my functions: <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getE ...

Updating Text in Textarea upon Selection Change

Need assistance with updating the content of a textarea based on a select option change. Below is an example of my code: <tr><td>Template:</td><td> <select t name="template" onChange = "setTemplate();"> <option ...

Update the display immediately upon a change in the state

In my app.js file, the code looks like this: export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.targ ...

What is the best way to access the latest value from a Vuex getter within a component's template

Is there a way to detect changes of the getter value within the template? I am using the following component: computed: { ...mapGetters({ processingStep: 'products/processingStep', }), <div class="col" v-if="pro ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

Using JSON to store the image URLs instead of encoding them in base64

I am currently utilizing Three.js to store and retrieve objects in a database. The objects are being inserted as JSON format. However, the issue I am facing is that when using JSON.stringify or toJSON(), it converts the image url (textures) into base64 fo ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

Encountering an illegal invocation type error when clicking on the search icon within a Vue component

I keep encountering an "illegal invocation" error in the console whenever I try to click on the search icon. 'focus' called on an object that does not implement interface HTMLElement. This error seems to occur intermittently. <div class=" ...

What is the most effective way to update the React state based on an if-else condition within a

I am facing an issue where I have a component in my project that needs to update the parent state when clicked, but there is an if-else condition causing the state not to update in the parent component. In my project, I have two boxes with an if-else cond ...

Tracking time in seconds and milliseconds with a stopwatch

Greetings! I am currently working on a reaction test to measure how quickly users react, and I seem to be struggling to find the necessary resources. I am curious about creating a basic stopwatch in seconds and milliseconds that can be triggered later by a ...

How can you make an element appear when clicking and then disappear with a second click?

Having a bit of an issue here. When I click on the menu button "x," it triggers an onclick event that opens/displays an element. All good so far. But now, I want to click the same menu button "x" to close that same element, and that's where I'm s ...

Stop HTML elements from shifting position when content is modified using JavaScript

'use strict'; const countdown = () => { // create function to calculate time until launch in Days/Hours/Minutes/Seconds // time difference const countDate = new Date('May 25, 2024 00:00:00').getTime(); const now = new Date( ...

The PHP time search function is experiencing technical difficulties and is not functioning correctly

I'm experiencing issues with adding a time search feature to my PHP site. The date search is functioning correctly, but when attempting to incorporate the time search, it doesn't seem to be working as expected. For instance, selecting 13:00 as t ...

Angular seems to be experiencing issues with maintaining context when executing a function reference for a base class method

Imagine we have CtrlOne that extends CtrlTwo, with a componentOne instantiated in the template of CtrlOne. Here is some code to illustrate the issue: class CtrlOne extends CtrlTwo { constructor() { super(); } } class CtrlTwo { sayMyName(name: st ...

Challenges with extracting and organizing dates using JavaScript regular expressions

My task involves organizing these text rows into specific groups based on certain criteria and names. Il Messaggero Roma 22 settembre 2023 Il Messaggero Roma 21 settembre 2023 Il Messaggero 22 settembre 2023 Il Messaggero 21 settembre 2023 Il Messaggero Ro ...

Identify Safari browser and redirect visitors

Here is the script I am using to detect and redirect a page specifically when Safari is used: if(/safari/.test(navigator.userAgent.toLowerCase())) { window.location.href = "elsewhere.html" } Currently, it redirects in both Safari and Chrome. How can ...

Is it considered acceptable in React for the value of one state to be determined by another state?

Consider this scenario: state1 tracks the mouseover of clientX and clientY, while state2 retrieves the value from state1 upon clicking. Is this implementation acceptable? const [move,setMove]=useState([]) const [click,setClick]=useState([]) useEffect(() ...

Try block must be followed by either a catch block or a finally

Currently, I am utilizing Node, Express with EJS view engine, nano for CouchDB, and encountering a perplexing error that I couldn't find any specific information about on Node or JavaScript via Stack Overflow or Google. The troublesome section of my c ...

Tips for injecting additional arguments into the JavaScript Array.forEach() function

Sharing a useful trick I discovered for passing variables into the scope of the JS Array.forEach() method. I recently encountered a scenario where I needed to iterate through a loop to create a dataset. However, I also needed to access variables within th ...