How to define and use directives on vue3 composition api with the new syntactic sugar in SFC <script setup> format?
With options API it used to be like this
import click_outside from "@/directives/click-outside.js";
export default {
directives: {
"click-outside": click_outside,
},
...
}
click-outside.js
<script setup>
import {defineProps, onBeforeMount, onUnmounted, directive } from "vue";
const onBeforeMount = (el, binding) => {
...
};
const onUnmounted = (el) => {
...
};
</script>
I couldn't figure out the same counterpart code in composition API
@Estus Flask's answer is enough but just to clarify, you just import directives like you do with components with PascalCase or camelCase and you can directly use it in your templates.
<script setup>
import vClickOutside from "@/directives/click-outside.js";
const outside = () =>{ ... }
...
</script>
<template>
...
<div v-click-outside="outside">
...
...
</template>
Feature parity with regular script SFC is achieved in 3 different ways.
props argument from setup and props, emits, expose fields from component options are provided by using define... helpers.
context (only slots and attrs properties) argument from setup is provided by using use... helpers.
components and directives are indirectly provided by using imports of the same name.
The rest of features (e.g. name property) are still provided by script element that can coexist with script setup.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With