Home > Enterprise >  VueJS define global function for child components
VueJS define global function for child components

Time:07-25

Can someone help me out configuring a global function that I can call in all my Vue files?

When there is this in my Vue file: @click="ModalShow.show('my-create')"

In the app.js I defined this constant:

const Modals = {
    show(screen) {
      alert(screen);
      // other logic that i implement that should be triggered
    },
};

But I keep getting: TypeError: undefined is not an object (evaluating '_ctx.Modals.show')

What am I missing? It's a Vue project with the composition API

CodePudding user response:

You can use provide/inject, first provide your function to your child components from the app (or parent component)

const Modal = {...}
const app = createApp({})
app.provide('Modal', Modal)

Then inject it into your component

import { inject } from 'vue'

export default {
  setup() {
    const Modal = inject('Modal')
    return { Modal }
  }
}
  • Related