关于vue的自定义指令使用场景问题

vue官方文档有自定义指令使用案例,可以有以下两个使用场景

1.懒加载图片

当你在阅览某网站的图片时,可能会由于图片资源比较大而加载缓慢,需要消耗一小段时间来呈现到眼前,这个体验肯定是不太友好的(就像网站切换页面,有时候会加载资源比较慢,为了给用户较好的体验,一般都会先出一个正在加载的友好提示页面),所以这个案例的功能就是在图片资源还没加载出来时,先显示默认背景图,当图片资源真正加载出来了之后,再把真实图片放置到对应的位置上并显示出来。

<div class="demo">
  <div v-for="item in imageList" :key="item.url">
    <img v-image="item.url" src="../assets/image/logo.png" alt="默认图">
  </div>
</div>
 
Vue.directive('image', {
  inserted: function(el, binding, vnode) {
    console.log('el', el) // 指令所绑定的元素,可以用来直接操作 DOM,就是放置指令的那个元素
    console.log('binding', binding) // 一个对象,里面包含了几个属性,这里不多展开说明,官方文档上都有很详细的描述
    console.log('vnode', vnode) // Vue 编译生成的虚拟节点
    // 为了真实体现效果,用了延时操作
    setTimeout(function() {
      el.setAttribute('src', binding.value)
    }, Math.random() * 1200)
  }
})
export default {
  data() {
    return {
      imageList: [
        {
          url: 'http://consumer-img.huawei.com/content/dam/huawei-cbg-site/greate-china/cn/mkt/homepage/section4/home-s4-p10-plus.jpg'
        },
        {
          url: 'http://consumer-img.huawei.com/content/dam/huawei-cbg-site/greate-china/cn/mkt/homepage/section4/home-s4-watch2-pro-banner.jpg'
        },
        {
          url: 'http://consumer-img.huawei.com/content/dam/huawei-cbg-site/en/mkt/homepage/section4/home-s4-matebook-x.jpg'
        }
      ]
    }
  }
}
 
2.校验按钮的权限
Vue.directive('permission', {
  inserted: function(el, binding, vnode) {
    const { value } = binding
    const permission = (store.getters && store.state.permission) || []
 // 如果操作按钮绑定值为字符串
    if (typeof value === 'string') {
      const hasPermission = permission.some(per => {
        return per === value
      })
      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else if (value instanceof Array) {
      // 如果操作按钮绑定值为数组
      const bool = value.some(item => {
        return permission.indexOf(item) > -1
      })
      if (!bool) {
        // 不存在就删除
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`权限指令出错`)
    }
  }
})
posted @ 2021-01-12 10:37  悟空不争宠  阅读(155)  评论(0)    收藏  举报