vue3实现自定义指令

创建一个empty.js

import { nextTick } from 'vue';
const emptyImgUrl = new URL('@/assets/images/empty-icon.jpeg', import.meta.url).href; // 在vue3中不支持require引入静态图片,这是一种引入方式 另外一种是直接import
const empty = {
  install(app, options) {
    app.directive('empty', (el, binding, vnode, oldVnode) => {
      nextTick(() => {
        let show = binding.value.show;
        let ElClass = binding.value.el;
        const _DOM = el.querySelector(`.${ElClass}`);
        if (!_DOM) {
          return;
        }
        if (show) {
          _DOM.style.display = 'block';
          const empty_content = el.querySelector('.empty_content');
          if (empty_content) empty_content.remove();
        } else {
          _DOM.style.display = 'none';
          let div = document.createElement('div');
          div.className = 'empty_content';
          div.style.height = '100%';
          div.style.width = '100%';
          div.style.display = 'flex';
          div.style.alignItems = 'center';
          div.style.justifyContent = 'center';
          let img = document.createElement('img');
          img.setAttribute('src', emptyImgUrl);
          div.appendChild(img);
          el.appendChild(div);
        }
      });
    });
  }
};
export default empty;

在main.js在引入:

import empty from './directive/empty';
app.use(empty);

在具体页面使用:

<div v-empty="{ el: 'empty', show: false }">
    <div class="empty"></div>
</div>

这样就完成了vue3自定义指令!

 
posted @ 2023-06-07 16:38  zaijinyang  阅读(352)  评论(0编辑  收藏  举报