vue-defu
v1.0.0
Published
A lightweight Vue directive to display a default placeholder text when an element and its children have no content.
Downloads
7
Maintainers
Readme
vue-defu
vue-defu
is a lightweight Vue directive that displays a default placeholder text when an element and its children have no content.
Installation
Install vue-defu
using npm:
npm install vue-defu
使用 / Usage
在 Vue 项目中注册并使用这个自定义指令: Register and use this custom directive in your Vue project:
import { createApp } from 'vue';
import DefuDirective from 'vue-defu';
const app = createApp({});
app.directive('defu', DefuDirective);
app.mount('#app');
示例 / Example
在 Vue 组件中使用指令: Use the directive in a Vue component:
<template>
<!-- hide '-' -->
<div v-defu="'-'">
<div></div>
<div>content</div>
</div>
<!-- show '-' -->
<div v-defu>
<div> </div>
<div></div>
</div>
</template>
<script setup>
import { createApp } from 'vue';
import DefuDirective from 'vue-defu';
const app = createApp({});
app.directive('defu', DefuDirective);
app.mount('#app');
</script>
API
v-defu
• 绑定值 / Binding Value: 字符串类型,指定当内容为空时显示的默认文案。例如:v-defu="'默认文本'"。
A string that specifies the default text to display when the content is empty. For example: v-defu="'Default text'".
常见问题 / FAQ
- 如何定制默认文案的样式? / How to customize the default text style?
默认文案的样式由动态创建的样式决定。你可以通过添加自定义 CSS 来调整文案的显示方式。
The default text style is defined by dynamically created styles. You can add custom CSS to adjust the display.
- 指令是否支持动态内容? / Does the directive support dynamic content?
是的,指令会在组件更新时重新检查内容并应用默认文案。
Yes, the directive rechecks the content on component updates and applies the default text accordingly.
not install
这只是个小工具, 你也可以不安装npm包, 直接复制代码到项目里使用
This is just a small tool. You can also copy the code directly into your project without installing the npm package.
// vdefu.js
export default {
mounted(el, binding) {
const defaultText = binding.value || "-";
const updateContentState = () => {
if (el.textContent.trim()) {
el.classList.remove("vdefu-show-default-text");
} else {
el.classList.add("vdefu-show-default-text");
el.setAttribute("data-default-text", defaultText);
}
};
updateContentState();
},
updated(el, binding) {
const defaultText = binding.value || "-";
el.setAttribute("data-default-text", defaultText);
const updateContentState = () => {
if (el.textContent.trim()) {
el.classList.remove("vdefu-show-default-text");
} else {
el.classList.add("vdefu-show-default-text");
el.setAttribute("data-default-text", defaultText);
}
};
updateContentState();
},
};
const style = document.createElement("style");
style.innerHTML = `
.vdefu-show-default-text::before {
content: attr(data-default-text);
display: inline;
}`;
document.head.appendChild(style);