Home > Software engineering >  How to make functions in <script setup > called by other components
How to make functions in <script setup > called by other components

Time:09-01

i have a function in < script setup > component, it not called in this component,i want use this function in other componet.

const playAudioType = (type) => {
          if (type === 'play') {
              store.setPlayStatus(!isPlayed.value);
              store.setPlayIndex(playIndex.value);
          } else {
              changeSong(type);
          }
      };

this code is grey in vs code

but when i use this function in other componet ,he can not recognize this function.

 const playSongStates = (state) => {
      audioRef.value.playAudioType(state);
    };

if use normal < script > i can return this function.

but in < scrtipt setup > how could i do

CodePudding user response:

You can use defineExpose to expose variables and methods from <script setup> to other components.

<script setup>
import { ref } from 'vue'

const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

In parent component:

      childRef.value.a

Further read

CodePudding user response:

As @manniL already wrote you can expose properties with defineExpose (https://vuejs.org/api/sfc-script-setup.html#defineexpose).

This only works within a parent-child relationship, and should normally not be used for reusable functions. The better solution would be to use composables (https://vuejs.org/guide/reusability/composables.html)

  • Related