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

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

What is the process for building .ts components within a Vue application?

Looking to update an old project that currently uses the 'av-ts' plugin and vue-ts-loader to compile .ts files as Vue components. The project is running on Vue 2.4.2, but I want to upgrade it to version 2.6.14. However, since 'vue-ts-loader& ...

Use jQuery to refresh the jQuery sparkline chart after fetching data asynchronously

Background Utilizing the jquery.sparkline library to generate Pie Charts. The data for these charts is stored in an array. Upon initial page load, a web-service call is made (using .ajax) to fetch the data. The callback function associated with this call ...

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

Can someone explain the meaning of this code?

Recently, I came across a project where this line of code was used in a jQuery script. I'm not sure of its purpose and would appreciate some help understanding why it was included. If necessary, I can provide the entire function for reference. $("#ta ...

When attempting to insert data retrieved from axios into a table within a React component, the data is coming back as

Hi there! Currently, I'm in the process of developing an application that retrieves data from an API and my goal is to display it in a Material UI Table within a React environment. Strange issue I'm encountering: when I use console.log to check ...

What is the process for executing mocha tests within a web browser?

Am I the only one who thinks that their documentation lacks proper instructions on running tests in the browser? Do I really need to create the HTML file they mention in the example? How can I ensure that it runs the specific test cases for my project? I ...

Animated CSS Checkmark Design

How can I create an animated Check-mark using CSS with SVG animation? I attempted the following code but it doesn't seem to be working. Any suggestions? DEMO: https://jsfiddle.net/b7Ln0jns/ CSS: @import "bourbon"; $color--green: #7ac142; $curve: c ...

Unable to show the input's value

Need help in taking user input to display calculated values //html <div class="empty"> <h5> Enter Empty Seats </h5> <ion-item> <ion-input placeholder="Enter Number of Empties.." type="number" name="emptySeats" [( ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

What is the most effective way to communicate to my client that attempting to conceal the browser toolbar is an ill-advised decision?

One of my clients has a friend who claims to be conducting 'security testing' and insists that the PHP Zend Framework application I developed for them should implement certain browser-side features: hide the location bar, toolbar, bookmarks, me ...

Adding new information into a database field through an HTML table

Can anyone help me figure out how to insert data from an HTML table into a MySQL database with the click of a button? Here is what my table looks like: <table> <tr> <th>Name</th> <th>Number</th> </tr> ...

Experiencing an unexpected wait before the requestAnimationFrame?

Surprisingly, Internet Explorer is actually performing the way I want it to in this case :-) I developed a function for SVG animations using requestAnimationFrame (for simplicity, I left out the value calculations here ... but my initial test involved an ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

excessive memory usage in a simple react-native application

My experience with creating my first react native app has been more challenging than I initially expected. I'm having trouble understanding what I might be doing wrong. Initially, the app is simple, fetching data through Redux. componentWillMount() ...

The partition.nodes(root) function in d3.js does not assign values to the x or dx properties of the nodes

I am currently experimenting with d3.js to create a unique icicle tree visualization using data sourced from a .json file. The challenge I'm facing lies in the fact that the x and dx attributes of the partition nodes are consistently being set to 0. M ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

The ajax method is encountering an issue when trying to perform an action: It is unable to find the necessary anti-forgery form field "__RequestVerificationToken" required for the operation

I am encountering an issue with my ajax method that triggers the action method from the controller. When I run this method, I receive an error stating: The required anti-forgery form field "__RequestVerificationToken" is not present. However, upon inspecti ...