3
votes

I'm trying to build a reusable modal component in Vue using this composition API. The plan is to expose a few methods like toggleModal() to call on some event in a parent component. I've written my method in both setup() and methods.

export default {
  setup() {
      const isModalOpen = ref(false);

      const toggleModal = () => {};

      return {
          toggleModal,
      };
  },
  methods: {
      toggleModalMethod() {},
  },
};

If I console.log() my modal component I can see that only my toggleModalMethod() from methods is exposed.

Is there a way to expose a child method and call it from a parent component?

1
In my experience it is not very good idea to call child component's method. For modal window it'll be better to use your own visible prop. In Vue we can send data to child with props only. Other way is to connect your modal to store variable. I think you not need to expose child methods to parent, using props is quite useful.Maksim Tikhonov
Isn't the purpose of the new api to have globally available things, why don't you make the modal subscribe to globally available data instead of trying to access an internal method? (You could do this with a store as well)Michael
@MaksimTikhonov I'm trying refactor a legacy app and move it away from vuex because it can manage without it. When creating the Modal component I thought of passing it a visible prop but became curious if I could create this componet with its self-contained logic since my app doesn't need to be aware of it globally nor its parent component. For that I'd need some exposed method to toggle its state. Is it a so-so idea?moshyfawn
It's not a bad idea, although as I wrote it seems that this is not what the api was meant for.Michael
@moshyfawn Sometimes I use service prop to trigger something in a child component. For ex., you may to declare trigger prop as number, and send to it Date.now() value when you need. In a child you will watching for trigger prop and when it changes, you will set localVisible to true for 3000 msMaksim Tikhonov

1 Answers

0
votes

It's expected that a property returned from setup will be available on component instance when a child is mounted.

Here is a demo:

<template>
  <div>
    <Modal ref="modal"/>
    <button @click="toggle">Toggle</button>
  </div>
</template>

<script>
...
export default {
  ...
  methods: {
    toggle() {
      this.$refs.modal.toggleModal();
    }
  }
};
</script>

Accessing child's members from a parent via a ref is considered an edge case, although exposing modal toggle function as public method is widely accepted scenario.