Open a Vuetify dialog from a component template in VueJS

前端 未结 8 1289
故里飘歌
故里飘歌 2020-12-02 11:27

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 butto

相关标签:
8条回答
  • 2020-12-02 12:05

    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 busand emit the event:

    <template>
      <div>
        <button @click.prevent="openMyDialog()">my button</button>
      </div>
    </template>
    
    <script>
      import {bus} from '../main' // import the bus from main.js or new file
      export default {
        methods: {
          openMyDialog () {
            bus.$emit('dialog', true) // emit the event to the bus
          }
        }
      }
    </script>
    

    In modal.vue also import the bus and listen for the event in the created hook:

    <script>
      import {bus} from '../main'    
      export default {
        created () {
          var vm = this
          bus.$on('dialog', function (value) {
            vm.dialog = value
          })
        }
      }
    </script>
    
    0 讨论(0)
  • 2020-12-02 12:05

    The most simpler way I found to do it is:

    in data() of component, return a attribute, let's say, dialog.

    When you include a component, you can set a reference to your component tag. E.g.:

    import Edit from '../payment/edit.vue';
    
    <edit ref="edit_reference"></edit>
    

    Then, inside my component, I have set a method:

            open: function () {
                var vm = this;
    
                vm.dialog = true;
            }
    

    Finally, I can call it from parent, using:

      editar(item)
      {
          var vm = this;
    
          vm.$refs.edit_reference.open();
      }
    
    0 讨论(0)
提交回复
热议问题