使用<script setup>写demo的时候尝试局部引入指令,代码如下
<template>
<h1 v-show="visible" v-click-outside="clickOut">{{ msg }}</h1>
</template>
<script setup>
import {reactive} from 'vue';
import clickOutside from 'directive/clickOutside.js';
const props = defineProps({
msg: String,
visible: Boolean
})
const emit = defineEmits(['close']);
const clickOut = () => {
console.log(`close`, 1111)
props.visible && emit('close');
}
</script>
但结果不尽如人意,报错如下
实际上应该用这种方式: import vClickOutside from 'directive/clickOutside.js';
划重点:vClickOutside重点就是这个v,需要v前缀的原因是,全局注册的指令(例如v-focus)很可能与本地声明的同名变量冲突。v前缀使使用变量作为指令的意图更加明确,并减少一些意外情况发生。
卡了半天,希望可以帮助踩坑的你
附上全局指令引入方式,和vue2区别不大
import longPress from 'directive/longPress';
import focus from 'directive/focus';
import App from './App.vue';
const app = createApp(App);
app.directive('longpress', longPress);
app.directive('focus', focus);
app.mount('#app');