Prevent direct prop mutation in Vuetify's Dialog component to prevent errors

I am facing an issue with my child component, a dialog box where I pass the prop dialog from the parent component. Whenever I try to close it by changing the prop value, I receive a warning. Can someone please guide me on the correct approach to resolve this problem?

<template>
  <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="dialog = !dialog">
            Disagree
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
export default {
  name: "EditOrder",
  props: ["order", "dialog"],
  data() {
    return {
      dialogCta: this.dialog,
    };
  },
  methods: {
    closeDialog() {
      // console.log(this.dialog);
      this.dialogCta = !this.dialog;
      console.log(this.dialogCta);
    },
  },
};
</script>

Answer №1

If you want to avoid directly modifying the prop, you can utilize a computed property that mirrors the value from the parent component and triggers an event on change to update it accordingly. Take a look at this demonstration:

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: () => ({ order: { fullname:"fullname", address:"address" }, dialog: true }),
  methods: {
    closeDialog(value) { this.dialog = value; }
  }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384e4d5d780a1640">[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="37414252435e514e7705194f">[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="b9dfd6d7cdf98d97c1">[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="ee989b8b9a878897aedcc096">[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">
  <dialogmodel v-model="dialog" :order="order" @close="closeDialog" />
</v-app>

Answer №2

<v-dialog v-model="dialog" max-width="290" persistent>
...
<v-btn color="green darken-1" text @click="dialog = !dialog">

When you interact with the code above, you are making changes to the dialog property

<template>
  <div>
    <v-dialog v-model="dialogCta" 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="dialogCta = false"> <!--  issue with changing the prop value here -->
            Disagree
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

export default {
  name: "EditOrder",
  props: [ "order", "dialog" ],
  data() {
    return {
      dialogCta: false
    }
  },
  watch: {
    dialog: {
      immediate: true,
      handler () {
        this.dialogCta = this.dialog
      }
    }
  },
  methods: {
    closeDialog() {
      console.log(this.dialogCta)
    }
  }
};

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

The unique capabilities of services and factories in Angular 1 - understanding their differences and what each excels at

After extensively combing through numerous stackoverflow posts and articles, the consensus seems to be that an angular service returns an instance, while an angular factory returns any desired object. This raises the question: what unique capabilities do ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

The website displays perfectly in Atom, however, it is not functional in any web browser

My website is currently in the development phase, and I'm experiencing issues with certain div elements not positioning correctly once the site goes live. Specifically, the "Follow Us" tab at the bottom of the site, among other divs, has been affecte ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

Having trouble with the placeholder blur feature on images in Next.js?

Within my website, I have a dynamic route set up as /titles/[slug].js. Upon initially navigating to this route, everything functions as expected - the placeholder blur effect displays on all images and animations triggered by react-intersection-observer wo ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

In a Vue component, use JavaScript to assign the data property in object 2 to object 1 when their keys match

Could use some assistance here as I believe I'm getting close to a solution, I have a form object that needs updating based on matching keys with an imported object. For example, form.title should be set to the value in article.title. I've att ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...

Utilizing Ajax data for CSS manipulation to display a live preview populated with form inputs

I am faced with a challenge involving a form containing approximately 80 input fields of type text and select. Each input field pertains to CSS values, and I aim to display a preview showcasing the new values (onChange any input value) in the form without ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Learn how to personalize the global navigation bar in Vue specifically for each view

Just diving into the world of Vue and I'm loving it so far. I've been working on a Vue-CLI app with a navbar and content, where the navbar is consistent across all pages. However, I want to spice things up by adding some unique content to the nav ...

Having trouble getting Three.js JSON models to cast shadows properly?

Recently, I've been experimenting with blender exported models in Three.js. I have successfully imported a model and observed how light interacts with the object. While a directionalLight is illuminating the front-facing parts, I'm facing an issu ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

Develop a list of findings from the search

Is there a way to extract the name from the image shown below? return testData.then((data) => { console.log(data) var results = []; var toSearch = params.suggestTerm; data = data["data"]["0"]; console.log(" ...

"Receiving the error message 'Object is not a function' occurs when attempting to pass a Node.js HTTP server object to Socket.IO

A few months back, everything was working fine when I set up an HTTPS server. Recently, I revisited the application and decided to switch to HTTP (though this change may not be directly related). In my code snippet below from 'init.js', I create ...

The Laravel broadcast()->toOthers() function seems to be malfunctioning as I am experiencing issues with duplicate messages despite using Laravel 8, Pusher, Laravel Echo, and VueJs 3

Currently, I am monitoring for the MessageSentEvent window.Echo.private("chat" + this.chat.id).listen( "MessageSentEvent", e => { var date = new Date().getTime(); this.lastMessageDate = moment() ...