How to call a method of component in plugin

Viewed 231

I made a component called dialog, and I want to make it plugin and register it as a global function.

However, I don't know how to access the component from plugin and call the component's method.

import Vue from 'vue'
import AlertDialog from '@/components/AlertDialog'

const methods = {
  openDialog: (
    maxWidth,
    title,
    message
  ) =>
    AlertDialog.openDialog(
      maxWidth,
      title,
      message
    ),
  closeDialog: () => AlertDialog.closeDialog()
}

Vue.prototype.openDialog = methods.openDialog
Vue.prototype.closeDialog = methods.closeDialog

This is a dialog_plugin.js.

But it doesn't work.

edit ::

<template>
  <v-dialog
    v-if="isShow"
    v-model="isShow"
    :max-width="maxWidth ? maxWidth : 290"
  >
    <v-card>
      ...
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  data() {
    return {
      isShow: false,
      maxWidth: null,
      title: null
    }
  },
  methods: {
    openDialog(
      maxWidth,
      title
    ) {
      this.isShow = true
      ...
    },
    closeDialog() {
      this.isShow = false
    }
  }
}
</script>

This is AlertDialog.vue

1 Answers

A component's methods are only intended to be called from within the component itself. Trying to expose them to be called by outside code is really going against the way Vue is designed to work.

If you want to affect the state of a component from outside of itself, there are a couple of ways:

  1. Props - Rather than isShow being a piece of the AlertDialog's state, you would pass this value in as a prop. That way the parent component can change the value to show/hide the alert as needed.

  2. Vuex - If you needed to have a single instance of a component in your app (e.g. for a toast display), having it receive its state from a Vuex store would make it easy to display messages from any part of your app.

  3. An Event Bus - For a simpler app where you don't want to bring in Vuex, you can always use an instance of Vue as an event bus, to control your component by emitting events from anywhere else in your app. Your component can then listen for these events and show/hide as needed.

Related