一、准备工作
1. 新建文件对自定义指令进行统一管理
src/directives/index.js:这个文件负责管理所有的自定义指令;
2. 自定义指令的基本语法
Vue.directive('指令名称', {
inserted: function (el, binding) {
}
})
二、定义自定义指令【v-img-error】
2.1 方式一 ➡ 使用 Vue.use() 注册
export const imgError = {
install (Vue) {
Vue.directive('imgError', {
inserted (el, binding) {
if (el.target.tagName !== 'IMG') return;
el.src = el.src || binding.value;
el.onerror = () => {
el.src = binding.value;
};
}
});
}
};
2.2 方式二 ➡ 使用 Vue.directive() 注册
export const imgError = {
inserted (el, binding) {
if (el.target.tagName !== 'IMG') return;
el.src = el.src || binding.value;
el.onerror = function () {
el.src = binding.value
}
}
}
三、注册自定义指令
2.1 方式一 ➡ 使用 Vue.use() 注册
import * as plugins from '@/directives';
Object.keys(plugins).forEach(key => {
Vue.use(plugins[key]);
});
2.2 方式二 ➡ 使用 Vue.directive() 注册
import * as directives from '@/directives'
Object.keys(directives).forEach(key => {
Vue.directive(key, directives[key])
})
四、使用自定义指令
<img v-imgError="defaultImg" :src="xxx">
data () {
return {
// 图片懒加载
defaultImg: require('默认图片的路径')
}
}