vue自定义指令

141 阅读1分钟

1.自定义v-hide指令 [core/directive.js]

import Vue from 'vue'
Vue.directive('hide', (el, binding, vnode) => {
    // console.log(binding, binding.value)
    el.style.visibility = 'hidden'
})

2.全局引入 [main.js]

import * as myDirectives from '@/core/directive'//自定义指令

new Vue({
  el: '#app',
  router,
  myDirectives,
  components: { App },
  template: '<App/>'
})

3.使用指令

<div v-hide></div>

4.实用的:自定义v-real-bgt指令

有很多时候可能需要展示背景图片,但是图片可能出现错误时使用

Vue.directive('real-bgt', async function (el, binding) {//指令名称为:real-bgt
    let imgURL = binding.value;//获取图片地址
    if (imgURL) {
        let exist = await bgtIsExist(imgURL);
        if (exist) {
            el.style.backgroundImage = `url(${imgURL})`
        }
    }
})

let bgtIsExist = function (url) {
    return new Promise((resolve) => {
        var img = new Image();
        img.onload = function () {
            if (this.complete == true) {
                resolve(true);
                img = null;
            }
        }
        img.onerror = function () {
            resolve(false);
            img = null;
        }
        img.src = url;
    })
}

图片可用,正常展示。图片不可用使用默认替代图片

<div
  class="pic"
  :style="{background:'url(' + 默认图片地址 + ') center no-repeat',backgroundSize: '100%'}"
  v-real-bgt="data.cover"
></div>