Incorporating a global confirm modal component into my default layout file has been a challenge. Attempting to access this component from my pages/index.vue has proven to be unsuccessful, as calling this.$refs returns an empty object. While placing the modal component directly in pages/index.vue technically resolves the issue, it defeats the purpose of having a global confirm modal in the first place.
layouts/default.vue
<template lang="pug">
v-app(v-if="show")
v-main
transition
nuxt
confirm(ref='confirm')
</template>
<script>
import confirm from '~/components/confirm.vue'
export default {
components: { confirm },
data: () => ({
show: false
}),
async created() {
const isAuth = await this.$store.dispatch("checkAuth")
if (!isAuth) return this.$router.push("/login")
this.show = true
}
}
</script>
components/confirm.vue
<template>
<v-dialog v-model="dialog" :max-width="options.width" @keydown.esc="cancel">
<v-card>
<v-toolbar dark :color="options.color" dense flat>
<v-toolbar-title class="white--text">{{ title }}</v-toolbar-title>
</v-toolbar>
<v-card-text v-show="!!message">{{ message }}</v-card-text>
<v-card-actions class="pt-0">
<v-spacer></v-spacer>
<v-btn color="primary darken-1" @click.native="agree">Yes</v-btn>
<v-btn color="grey" @click.native="cancel">Cancel</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script>
export default {
data: () => ({
dialog: false,
resolve: null,
reject: null,
message: null,
title: null,
options: {
color: 'primary',
width: 290
}
}),
methods: {
open(title, message, options) {
this.dialog = true
this.title = title
this.message = message
this.options = Object.assign(this.options, options)
return new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
},
agree() {
this.resolve(true)
this.dialog = false
},
cancel() {
this.resolve(false)
this.dialog = false
}
}
}
</script>
My goal is to invoke this modal from pages/index.vue as follows (the ref placement here works, but I aim to have a globally accessible confirm modal):
methods: {
async openConfirm() {
console.log("openConfirm")
if (await this.$refs.confirm.open('Delete', 'Are you sure?', { color: 'red' })) {
console.log('--yes')
}else{
console.log('--no')
}
},