I’m using the VueJS Vuetify framework and I need to open a dialog – that gets imported as a component template – from another template. Once the Menu button in App.vue got clicked, the Modal should open. Here is my setup:
- App.vue = navigation template with Menu button
- Modal.vue = Modal template, imported as global in main.js
main.js
JavaScript
x
3
1
import Modal from './components/Modal.vue'
2
Vue.component('modal', Modal)
3
Modal.vue Template:
JavaScript
1
26
26
1
<template>
2
<v-layout row justify-center>
3
<v-btn color="primary" dark @click.native.stop="dialog = true">Open Dialog</v-btn>
4
<v-dialog v-model="dialog" max-width="290">
5
<v-card>
6
<v-card-title class="headline">Use Google's location service?</v-card-title>
7
<v-card-text>Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running.</v-card-text>
8
<v-card-actions>
9
<v-spacer></v-spacer>
10
<v-btn color="green darken-1" flat="flat" @click.native="dialog = false">Disagree</v-btn>
11
<v-btn color="green darken-1" flat="flat" @click.native="dialog = false">Agree</v-btn>
12
</v-card-actions>
13
</v-card>
14
</v-dialog>
15
</v-layout>
16
</template>
17
<script>
18
export default {
19
data () {
20
return {
21
dialog: false
22
}
23
}
24
}
25
</script>
26
How to open the dialog?
Advertisement
Answer
You can open the dialog using custom events and using an event bus for non parent-child communication.
If your application gets a bit more complex I recommend you use Vuex for state management.
Event bus solution:
In your main.js or in a new file create and export a new Vue instance :
export const bus = new Vue()
In app.vue import the bus
and emit the event:
JavaScript
1
17
17
1
<template>
2
<div>
3
<button @click.prevent="openMyDialog()">my button</button>
4
</div>
5
</template>
6
7
<script>
8
import {bus} from '../main' // import the bus from main.js or new file
9
export default {
10
methods: {
11
openMyDialog () {
12
bus.$emit('dialog', true) // emit the event to the bus
13
}
14
}
15
}
16
</script>
17
In modal.vue also import the bus and listen for the event in the created hook:
JavaScript
1
12
12
1
<script>
2
import {bus} from '../main'
3
export default {
4
created () {
5
var vm = this
6
bus.$on('dialog', function (value) {
7
vm.dialog = value
8
})
9
}
10
}
11
</script>
12