Having trouble getting the Vue.js Element-UI dialog to function properly when embedded within a child component

Take a look at the main component:

<template lang="pug">
  .wrapper
    el-button(type="primary", @click="dialogAddUser = true") New User
    hr
    // Dialog: Add User
    add-edit-user(:dialog-visible.sync="dialogAddUser")
</template>

<script>
import * as data from '@/components/partials/data'
import AddUser from './partials/AddUser'

export default {
  name: 'users',
  components: { AddUser },

  data () {
    return {
      users: data.users,
      dialogAddUser: false
    }
  }
}
</script>

And now, let's dive into the child component:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible.sync="dialogVisible", top="5vh")
    div 'el-dialog-body' - content goes here
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    }
  }
</script>

Opening the dialog works fine, but when trying to close it using the top right button inside the dialog, an error occurs:

Avoid directly mutating a prop as its value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. The prop being mutated is "dialogVisible"

I attempted to troubleshoot by making changes like so, but unfortunately, I am now unable to open the dialog at all:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible.sync="visibleSync", top="5vh")
    div 'el-dialog-body' - content goes here 
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    },
    watch: {
      visibleSync (val) {
        this.$emit('update:dialogVisible', val)
      }
    },
    data () {
      return {
        visibleSync: this.dialogVisible
      }
    }
  }
</script>

Answer №1

If the visible.sync feature is functioning correctly, it means that the component is triggering an update:visible event.

In order to avoid mutating in the child and instead pass the event to the parent, you can replace:

:visible.sync="dialogVisible"

With:

:visible="dialogVisible", v-on:update:visible="visibleSync = $event"

Here is the complete code snippet:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible="dialogVisible", v-on:update:visible="visibleSync = $event", top="5vh")
    div 'el-dialog-body' - content goes here 
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    },
    watch: {
      visibleSync (val) {
        this.$emit('update:dialogVisible', val)
      }
    },
    data () {
      return {
        visibleSync: this.dialogVisible
      }
    }
  }
</script>

Alternatively, you can also emit directly from the v-on listener and eliminate the need for the visibleSync local property:

<template lang="pug">
  el-dialog(width="75%", title="New User", :visible="dialogVisible", v-on:update:visible="$emit('update:dialogVisible', $event)", top="5vh")
    div 'el-dialog-body' - content goes here 
</template>

<script>
  export default {
    name: 'add-user',
    props: {
      dialogVisible: Boolean
    }
  }
</script>

Answer №2

One effective way to tackle this situation would be:

  1. Utilize a prop to transfer the visible state from the parent component to the child component.
  2. Pass the close event of el-dialog from the child to the parent component.
  3. In the parent component, manage the close event to update the prop as false.

Child Component Example:

<el-dialog :visible="visible" @close="$emit('close')">
export default {
  props: {
    visible: Boolean
  },
  ...

Parent Component (assuming the open state is stored in state.modalOpen):

<el-button @click="state.modalOpen = true">Open Modal</el-button>
<child-component :visible="state.modalOpen" @close="state.modalOpen = false" />

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

When using $state.go in $stateChangeStart, there is a dual state transition in ui-router

Take a look at my Plunker. When you click on the profile link and examine the list of state changes: stateChanges = [ " -> home", "home -> profile", "home -> signIn", "signIn -> signIn" ] You'll notice an unexpected extra state c ...

Fetch routes from an external API using a component and integrate them seamlessly into the router

I want to fetch my routes from an external API, considering that some users may not have the necessary permissions to access a particular module. My navbar makes an API request to retrieve all available modules. These modules contain the file path for the ...

Which directories and files are necessary in a Laravel project when using Vue and Vuetify?

Recently, I've been delving into the world of Laravel, Vue, and Vuetify in an attempt to broaden my skills. However, despite my best efforts, I have struggled to find a comprehensive guide that actually works for installing these technologies successf ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

Is there a way to extract a single value from an array of data and convert it into a series of values separated by commas, all using JavaScript but without

Here is an array data in a specific format: const data= [ { name: "productname", id: "1356", price: "0.00", category: "Health", position: "1", list: "New Products", ...

Is that file or directory non-existent?

While working on developing a Discord bot, I keep encountering an error message stating: "Line 23: no such file or directory, open 'C:\Users\Owner\Desktop\Limited Bot\Items\Valkyrie_Helm.json']" even though the filep ...

Utilize Knex - incorporating withGraphFetched and a filter condition in your query

My task involves querying the database with Knex to retrieve sales data from a specific city. Here are the two tables I am working with: sale: id drugstore_id drugstore: id name city Below are my model definitions: class Sale extends Model { static mo ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have: <select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)"> <option>select people</option> <option *ngFor="let x of peopleList" [ngValue]="x"> ...

The application is resetting when the "$http" method accesses the initial ADAL "protected" URL for the first time

I have created a page inspired by the Angular SPA ADAL sample which can be found here Upon returning from the Microsoft login page and accessing my API secured with AAD, the angular .config() function is called multiple times. This causes issues with upda ...

Utilizing jQuery to extract the `h1` element from a dynamically loaded external page within the

I am facing a challenge in selecting an h1 element from a remote page that I have loaded into $(data). Despite several attempts, I am struggling to write the correct code. When I use this code: console.log($(data)); The output is as follows: [text, meta ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

Incorporating RFID reader functionality into a website

I am currently facing an issue with integrating an RFID card reader into a web page. After some research, it seems that the solution involves creating an ActiveX component and using JavaScript. My question is, how can we go about building an ActiveX compo ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Personalized dropdown filters for Bootstrap Datatable

In my codeigniter project, I am utilizing Bootstrap datatables. In the footer section, I have included the datatables js and initialized it like so: $('.datatable').dataTable({ "sDom": "<'row-fluid'<'span6'l ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

Why is my Cloud Storage Cloud upload file showing a file size of "0 bytes" (Node)?

I am having issues uploading a PDF file to Google Cloud Storage as the file size appears to be 0 bytes. I have been trying to resolve this for the past 3 days but have not received any response. Here is the code snippet that I am using: const cv = req ...

What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request. Take for instance my model: //order.model.ts export class Order { constructor(public id: num ...

Guide on Fetching an Image from a Server with Vue Js

I am trying to fetch an image from the server using Vue.js and Laravel. Below is my code: Controller public function index() { $posts = Post::all(); return response()->json(["posts" => $posts]); } Router Route::get('test','Mas ...

The component encounters a transformation in which prop values shift to undefined

My component seems to be encountering some instability. The value assigned to "this.state.list" from this.props is being immediately set to "undefined". I'm struggling to comprehend why this is happening. Can anyone spot the issue in the code? this.s ...