流浪のwolf

卷帝

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

v-imgerror作用:当图片链接无效的时候,显示默认图片内容

复制代码
// 回顾自定义指令
// 作用: 自定义一些对DOM的操作快捷指令
// 前提: 指令就是用来操作DOM (v-if/v-show/v-for....)

// 语法: Vue.directive(指令名,{ 配置对象 })
// 使用: <标签 v-指令名="表达式/变量" />
// import Vue from "vue";

// ======================>在这个文件里面只有按需导出,没有默认
// v-imgerror作用:当图片链接无效的时候,显示默认图片内容
export const imgerror = {
  // el指令所在的DOM节点
  // binding指令包含的相关信息
  inserted(el, binding) {
    // console.log(el); // 图片节点
    // console.log(binding);
    // 图片有个原生事件叫做onerror,即加载资源失败事件
    // 一旦图片加载失败,则调用这个函数
    el.src = el.src || options.value;
    el.onerror = function () {
      this.src = binding.value;
    };
  },
  componentUpdated(el, options) {
    el.src = el.src || options.value;
  },
};

export const aaa = {
  inserted() {},
};

export const bbb = {
  inserted() {},
};

// Vue.directive("imgerror", imgerror);
// Vue.directive("aaa", aaa);
// Vue.directive("bbb", bbb);
复制代码

在main.js 中引入文件

// 导入自定义指令文件
import * as directive from "@/directive";
// 批量注册自定义指令
Object.keys(directive).forEach((item) => {
  // item就是模块里面每个暴露的属性名   directive[item] 就是每个属性的值
  Vue.directive(item, directive[item]);
});

 

posted on   朱龙旭的网络  阅读(108)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· 支付宝 IoT 设备入门宝典(下)设备经营篇
· 万字调研——AI生成内容检测
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
点击右上角即可分享
微信分享提示