I want to create a directive which enables me to save component references of a certain type into an array. The functionality is quite easy:
- on mounted: add element to a given array
- on unmounted: remove the exact same element from the array
Link to the playground: https://stackblitz.com/edit/github-mmhfcj
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.directive('formRef', {
mounted(el, binding) {
console.log(binding.instance);
binding.value.push(el);
},
unmounted(el, binding) {
const foundIndex = binding.value.findIndex(
(item: any) => item.name === el.name
);
if (foundIndex !== -1) {
(binding.value as Array<any>).splice(foundIndex, 1);
}
},
});
});
The usage of the directive:
<template>
<div>
<AccessMe name="bruh" v-formRef="elements" />
</div>
</template>
<script lang="ts" setup>
const elements = ref([]);
</script>
the AccessMe component:
<template>
<div>
{{ props.name }}
</div>
</template>
<script lang="ts" setup>
const props = defineProps<{
name: string;
}>();
function getName() {
return 'my name is' + name;
}
defineExpose({ getName });
</script>
Why is the instance always an empty object and not the component itself with the prop name and the defined function?