Display a dialogue box when encountering a Vuetify error. Only open the dialogue box under certain conditions

I am currently implementing vuetify into my project. The main issue I am facing is related to the dialog component, which I only want to open in case of an error. The scenario involves a button calling a backend service to save a product in the database, and if a duplicate product is detected, it fails. However, at the moment, the dialog opens with the error message every time the button is clicked. My goal is to have the dialog open conditionally - displaying a success dialog upon success and an error dialog when there is an error.

<template>
  <div>
    <v-card v-show="createProducts">
      <v-toolbar card prominent color="primary" dark>
        <v-toolbar-title>Create Product</v-toolbar-title>
      </v-toolbar>
      <v-card-text>
        {{ product }}
        <v-form ref="form" v-model="valid" lazy-validation>
          <v-container>
            <v-layout row wrap>
          <v-flex xs6>
          <v-text-field
            v-model="product.name"
            label="Product Name"
            v-validate="'required'"
            required
            solo=""
            data-vv-name="product name"
            :error-messages="errors.collect('product name')"
          ></v-text-field>
          </v-flex>

          <v-flex xs6>
          <v-text-field
            v-model="product.code"
            label="Product Code"
            v-validate="'required'"
            required
            solo=""
            data-vv-name="product code"
            :error-messages="errors.collect('product code')"
          ></v-text-field>
          </v-flex>

          <v-flex xs12>
          <v-textarea
            v-model="product.description"
            :auto-grow="true"
            :box="false"
            solo
            :autofocus= "true"
            :outline="false"
            color="black"
            background-color="white"
            label="Product Description"
            rows="3"
          ></v-textarea>
          </v-flex>

         
          <v-flex xs12>
          <v-select
            :items="dashboard"
            label="Dashboard Template"
            v-model="product.dashbaord"
            data-vv-name="dashboard"
            v-validate="'required'"
            required
            solo=""
            :error-messages="errors.collect('template')"
          ></v-select>
          </v-flex>

          <!-- Conditional Dialog Box -->

    <v-dialog  v-model="dialog" width="500">
      <v-btn slot="activator" color="primary" @click="createNewProduct" center>Save</v-btn>
        <v-card>
          <v-card-title class="headline grey lighten-2" primary-title>Error</v-card-title>

          <v-card-text>Product Code already exists</v-card-text>

          <v-divider></v-divider>

          <v-card-actions>
            <v-spacer></v-spacer>
           <v-btn color="blue darken-1" flat @click="dialog= false">No</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>


            </v-layout>
          </v-container>
        </v-form>
      </v-card-text>
    </v-card>
  </div>
</template>

<script>
import RestResource from "../services/dataService.js";
const service = new RestResource();

export default {
  name: "createProducts",
  data() {
    return {
      createProducts: true,
      valid: true,
      product: {},
      dialog: false,
      dashboard: [
        "Template1",
        "Template2",
        "Template3",
        "Template4",
        "Template5",
        "Template6"
      ]
     
    }
    
  },

  methods: {
    async createNewProduct() {
      let validation = await this.$validator.validateAll();
      console.log(`validation :: ${validation}`)

      if (validation) {
      
      let response = await service.createProduct(this.product).then(result => {
      alert("Done..." + result);
        
      }).catch (error => {
        alert("Failed..." + error);
        
      })
      // this.$router.push({ name: "products"});    
      }
    }
  },


};
</script>

Answer №1

If you want to display the dialog, simply set this.dialog = true

async createNewProduct() {
  let isValid = await this.$validator.validateAll();
  console.log(`validation :: ${isValid}`)
  var currentObj = this
  if (isValid) {

    let response = await service.createProduct(this.product).then(result => {
      alert("Success: " + result);

    }).catch(error => {
      alert("Failed: " + error);
      currentObj.dialog = true
    })
    // this.$router.push({ name: "products"});    
  }
}

Answer №2

After some trial and error, I finally cracked the code! By implementing v-show within our v-cards and toggling between success and failure states, we can easily trigger the corresponding methods based on our requirements.

<template>
  <div>
    <v-card v-show="createProducts">
      <v-toolbar card prominent color="primary" dark>
        <v-toolbar-title>Create Product</v-toolbar-title>
      </v-toolbar>
      <v-card-text>
        {{ product }}
        <v-form ref="form" v-model="valid" lazy-validation>
          <v-container>
            <v-layout row wrap>
          <v-flex xs6>
          <v-text-field
            v-model="product.name"
            label="Product Name"
            v-validate="'required'"
            required
            solo=""
            data-vv-name="product name"
            :error-messages="errors.collect('product name')"
          ></v-text-field>
          </v-flex>

          <v-flex xs6>
          <v-text-field
            v-model="product.code"
            label="Product Code"
            v-validate="'required'"
            required
            solo=""
            data-vv-name="product code"
            :error-messages="errors.collect('product code')"
          ></v-text-field>
          </v-flex>

          <v-flex xs12>
          <v-textarea
            v-model="product.description"
            :auto-grow="true"
            :box="false"
            solo
            :autofocus= "false"
            :outline="false"
            color="black"
            background-color="white"
            label="Product Description"
            rows="3"
          ></v-textarea>
          </v-flex>


          <v-flex xs12>
          <v-select
            :items="dashboard"
            label="Dashboard Template"
            v-model="product.dashbaord"
            data-vv-name="dashboard"
            v-validate="'required'"
            required
            solo=""
            :error-messages="errors.collect('template')"
          ></v-select>
          </v-flex>

          <!-- dialog box -->

    <v-dialog v-model="dialog" width="500">
      <v-btn slot="activator" color="primary" @click="createNewProduct" center>Save</v-btn>
      
            <!-- When product is successfully added -->
       <v-card v-show="success">

          <v-card-title class="headline grey lighten-2" primary-title>Success</v-card-title>

          <v-card-text>Product Successfully Added</v-card-text>

          <v-divider></v-divider>

          <v-card-actions>
            <v-spacer></v-spacer>
           <v-btn color="blue darken-1" flat @click="showProductList">Continue</v-btn>
          </v-card-actions>
        </v-card>
      
      
      <!-- When there is an error -->
      
        <v-card v-show="failure">
          <v-card-title class="headline grey lighten-2" primary-title>Error</v-card-title>

          <v-card-text>Product Code already exists</v-card-text>

          <v-divider></v-divider>

          <v-card-actions>
            <v-spacer></v-spacer>
           <v-btn color="blue darken-1" flat @click="dialog= false">No</v-btn>
          </v-card-actions>
        </v-card>

      </v-dialog>


            </v-layout>
          </v-container>
        </v-form>
      </v-card-text>
    </v-card>
  </div>
</template>

<script>
import RestResource from "../services/dataService.js";
const service = new RestResource();

export default {
  name: "createProducts",
  data() {
    return {
      createProducts: true,
      valid: true,
      product: {},
      dialog: false,
      success: false,
      failure: false,
      dashboard: [
        "Template1",
        "Template2",
        "Template3",
        "Template4",
        "Template5",
        "Template6"
      ]
     
    }
    
  },

  methods: {
    async createNewProduct() {
      let v = await this.$validator.validateAll();
      console.log(`validation :: ${v}`)

      if (v) {
      
      let a = await service.createProduct(this.product).then(r => {
      alert("Done..." + r);
      // this.success = true
      this.$router.push({ name: "products"}); 
      
        
      }).catch (e => {
        alert("Failed..." + e);
        this.failure = true
        
      })
         
      }
    }
  },


};
</script>

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

JQuery post request not providing the expected response after posting

I have a post request var prodId = getParameterByName('param'); var pass = $('#password1').val(); $.post("rest/forget/confirm", { "param" : prodId, "password" : pass }, function(data) { ...

Guide to implementing dynamic conditional rendering in Vue.js loops (utilizing v-if within v-for)

I am currently working on a table component in a .vue file where I want to display icons based on the direction of the order clicked. For example: <th v-for="(column, index) in columns" :key="index" @click="sort( index )"> <span& ...

What is the most effective way to programmatically recreate scope in AngularJS?

Currently, I am working on implementing UI-router to handle state changes in my application. My initial belief was that switching states on a dynamic route would result in the current scope getting destroyed and a new scope being created for the template w ...

AngularJS directive for jQuery Handsontable is a powerful tool for creating interactive

I've been experimenting with using jQuery handsontable in conjunction with an angular directive, but I've encountered a strange issue. Whenever I type something into the cells, the characters appear outside of the table instead of inside it. Oddl ...

Tips for overlaying an image on a div regardless of its height

(!) Although this question may seem repetitive, I have not been able to find a suitable solution in any of the previous 10 topics. I apologize for the inconvenience and am actively seeking a resolution to this unique situation; Allow me to outline the iss ...

transmitting comfort through events

To enhance my application, I am working on publishing a solace message to a topic and then passing it along to another part of the app for further processing using events. This entire process is happening within a single node.js process. While I understand ...

Utilizing numerous occurrences of my personalized Angular JS Directive within the identical form

I've been struggling to find a solution for this particular issue. On my webpage, I have two instances of a directive that are supposed to set values for two different text fields. However, when I select one value, the other field automatically chang ...

Setting a displacement/normal map for only one face of a cylinder

My current setup involves creating a cylinder using the following code: var geometry = new THREE.CylinderGeometry( 50, 50, 2, 128 ); The resulting shape is a flat cylinder resembling a coin. However, when I apply a displacementMap and normalMap, I notice ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

What's causing these divs to be misaligned in various directions?

I am currently working with a front-end framework based on flexbox called Material-UI, and I have noticed that the layout of certain components, particularly the quantity control elements, appears to be different even though they all share the same styling ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Implementing Bootstrap tooltips in content that can be scrolled

I need help with positioning two containers, which you can view in this FIDDLE. Both containers may contain a lot of content, so I have applied overflow: auto to both of them. This is the HTML structure: <div id="maincontainer"> <d ...

Managing embedded URLs in Next.js applications

I am currently in the process of developing an ecommerce platform, expecting users to utilize both our domain and their own custom domains. For example: ourplatform.com/username theirdomain.com My goal is to customize the inline links based on the speci ...

The problem I'm facing is that all the data is being received, except for the name, when I start with the success

When I add parameters to the success URL, all data comes through, but when I add a name, it gives an error. I've noticed that if I remove the spaces between letters, it works fine. However, I want to make it function properly. Can you assist me with t ...

What is the best way to switch back and forth between two div elements?

I've been attempting to switch between displaying div .cam1 and div .cam2, however, I can't seem to get it to work. Here's the code snippet in question: HTML: <div class="cam1"></div> <div class="cam2"></div> CS ...

Tips for creating unique names for JSON data modification functions

I have some data stored in JSON format that I need to slightly rearrange before sending it to the client. What should I name the function responsible for this reordering? Is serializeSomething a suitable choice? From what I understand, serialization invo ...

Loading website with continuous HTML5 video playback

I'm currently working on a website that features a large section with a video background set to loop. To enhance the user experience, we decided to include a preloading image while the site loads its resources. Our current setup involves using jQuery ...

Getting dynamic props from a clicked element in React involves accessing the target element's properties and

I am currently working with a React "tree" menu component that has main links with submenus generated dynamically through a JSON GET call. Upon inspecting the tree in the React Inspector, I noticed that each element has multiple props associated with it. H ...

Issue with Netlify's Continuous Deployment

Utilizing netlify as a platform to host my spa vue application has been a great experience overall. However, I have noticed that when I push changes triggering a rebuild, it seems to disrupt some of the functionality in instances of the application current ...