//正确使用
<div v-empty="isEmpty">
<div>内容xxxx</div>
</div>
//错误使用
<div v-empty="isEmpty">内容xxxx</div>
实现思路:将添加指令的dom的所有一级子元素(非孙子)dispaly:none,并在末尾添加空状态组件。
import MyEmpty from '@/common/components/empty/index.vue' //空状态组件(可根据自己项目确定)
const empty = {}
empty.install = function (Vue) {
Vue.directive('empty', function (el, binding) {
const isEmpty = binding.value
const uniqueId = 'empty-container-uniqueId753159876' // 生成ID
if (isEmpty) {
// 检查当前元素的儿子节点(不包括孙子节点)是否已经添加过“暂无数据”的节点
const existingEmptyElement = Array.from(el.children).find(child => child.id === uniqueId)
if (existingEmptyElement) {
return // 如果已经存在,则直接返回,不再添加
}
// 隐藏当前元素的所有子元素
Array.from(el.childNodes).forEach(child => {
child.style.display = 'none'
})
const EmptyConstructor = Vue.extend(MyEmpty)
const instance = new EmptyConstructor()
// 添加“暂无数据”组件
const component = instance.$mount()
component.$el.id = uniqueId //el中只有一个empty
el.appendChild(component.$el)
} else {
// 显示所有子元素
Array.from(el.childNodes).forEach(child => {
child.style.display = ''
})
//删除空状态元素
const children = Array.from(el.childNodes)
if (children.length > 0) {
const lastChild = children[children.length - 1]
if (lastChild.id === uniqueId) el.removeChild(lastChild)
}
}
})
}
export { empty }
Vue.use(empty)