44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
|
|
import type { Directive, DirectiveBinding } from 'vue'
|
|||
|
|
import { useConfigStoreHook } from '@/stores'
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 开发模式专用指令
|
|||
|
|
* 只在开发模式下显示元素,生产模式下会移除该元素
|
|||
|
|
*
|
|||
|
|
* \@param binding.value - 是否开启该功能,默认为 true
|
|||
|
|
* @example
|
|||
|
|
* \!-- 默认开启,开发模式显示 --
|
|||
|
|
* \!div v-dev-only开发模式内容</div>
|
|||
|
|
*
|
|||
|
|
* \!-- 传入参数控制 --
|
|||
|
|
* <div v-dev-only="true">开启指令</div>
|
|||
|
|
* <div v-dev-only="false">取消指令</div>
|
|||
|
|
*/
|
|||
|
|
export const devOnly: Directive = {
|
|||
|
|
mounted(el: HTMLElement, binding: DirectiveBinding) {
|
|||
|
|
checkAndRemoveElement(el, binding)
|
|||
|
|
},
|
|||
|
|
|
|||
|
|
updated(el: HTMLElement, binding: DirectiveBinding) {
|
|||
|
|
checkAndRemoveElement(el, binding)
|
|||
|
|
},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const configStore = useConfigStoreHook()
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 检查并移除元素的逻辑
|
|||
|
|
*/
|
|||
|
|
function checkAndRemoveElement(el: HTMLElement, binding: DirectiveBinding) {
|
|||
|
|
const isDev = typeof configStore.config.dev === 'boolean' ? configStore.config.dev : import.meta.env.DEV
|
|||
|
|
// 默认值为 true,如果没有传值或者传值为 true 都启用
|
|||
|
|
const shouldEnable = binding.value !== false
|
|||
|
|
// 如果不是开发模式或者明确禁用,移除该元素
|
|||
|
|
if (!isDev && shouldEnable) {
|
|||
|
|
console.log(1111)
|
|||
|
|
if (el.parentNode) {
|
|||
|
|
el.parentNode.removeChild(el)
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|