Tuesday 11 May 2021

Vue.js How to close a v-dialog box from inside the component.


This is easy enough to do when you have all your code on one page. You can set a value in ‘data’ of the script and then set that to either true or false to open and close the box. Take this example of my Message box, also note how you can manipulate the message and colors to your needs rather than rewriting. HTML


<v-snackbar v-model="snackbar" :timeout="4000" top :color="error_message_color">
<span>{{ error_message }}</span>
<v-btn outlined @click="snackbar = false">Close</v-btn>
</v-snackbar>




SCRIPT 

export default {
data() {
return {
...
snackbar: false,
error_message: "Awesome! You've updated this users roles.",
error_message_color: 'success'
};
},

// to fire this snackbar up from a method you just need to add ->
this.snackbar = true;

// if you want to fire up with a different message other than the defaults

if ( currentUser.email === Profile.email && action === 'remove' && role.toLowerCase() === 'admin'){
this.error_message_color = 'error';
this.error_message = 'Admins cannot remove their own admin role.';
this.snackbar = true;
return;
}

 However, although this code is good on one page if we’ve opened up the Dialog from a parent page like the following then unfortunately that won’t work.


// HTML
<RolesDialog :profile="profile" />

//SCRIPT
import RolesDialog from './RolesDialog.vue'

export default {
components: {
RolesDialog
},
data() {
return {
roles_dialog: false
};

With the above code, we cannot shut the box from our v-dialog box that we’ve opened.

The following code should work, and that works using $emit

Our call to the component.

<RolesDialog :profile="profile" @close-dialog="closeDialog" />

SCRIPT


data() {
return {
...
dialog: false,
roles_dialog: false
};
},

methods: {
closeDialog: function(){
console.log('close dialog 2');
this.dialog = false;
this.roles_dialog = false
}
},
}

In the CHILD component.


// HTML

<v-btn
color="blue darken-1"
text
@click="closeDialog"
>

// SCRIPT

methods: {
closeDialog: function(){
console.log('close dialog 1');
this.$emit('close-dialog')
}
}

  This should now work.












No comments: