1.局部使用
directives
<template>
<div id="app">
修改图片的代码 <img v-imgerror="defaultSrc" :src="imgSrc" alt="">
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
// 修改图片的方法
directives: {
imgerror: {
// 第一次拿到的图片值.如果没有就给它一个默认的值
inserted(dom, obj) {
dom.src = dom.src || obj.value
dom.onerror = function() {
dom.src = obj.value
}
},
// 当更新以后需要再次判断.是否有新的图片
componentUpdated(dom, obj) {
dom.src = dom.src || obj.value
},
//更新完毕后解绑
unbind(dom) {
dom.onerror = null
}
}
},
data() {
return {
imgSrc: '123',
defaultSrc: 'head.jpg'
}
}
}
</script>
<style lang="scss" scoped>
img{
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
2.全局使用
// 自定义全局指令更新图片
Vue.directive('imgerror', {
inserted(dom, obj) {
dom.src = dom.src || obj.value
dom.onerror = function() {
dom.src = obj.value
}
},
// 更新时重新赋值
componentUpdated(dom, obj) {
dom.src = dom.src || obj.value
},
// 更新完毕以后销毁之前的值
unbind(dom) {
dom.onerror = null
}
})
3.单独抽离注册使用
一般创建在src下.directive文件下的index.js
export default {
imgerror: {
// 渲染时的生命周期
inserted(dom, obj) {
dom.src = dom.src || obj.value
dom.onerror = function() {
dom.src = obj.value
}
},
// 更新时生命周期重新赋值
componentUpdated(dom, obj) {
dom.src = dom.src || obj.value
},
// 销毁 更新完毕以后销毁之前的值
unbind(dom) {
dom.onerror = null
}
}
}
在main.js中引入 自定义指令一般不止一个.所以使用以下方法.
import directiverJs from '@/directive'
//当自定义属性大于等于1个时
for (const key in directiverJs) {
Vue.directive(key, directiverJs[key])
}
方法二.推荐
import directiverJs from '@/directive'
// 数组的使用方法
// Object.keys({ a: 1, b: 2 }) === [a, b]
// Object.values({ a: 1, b: 2 }) === [1, 2]
// Object.entries({ a: 1, b: 2 }) === [[a, 1], [b, 2]]
Object.keys(directiverJs).forEach(item => {
Vue.directive(item, directiverJs[item])
})
最后在页面中使用.
<img v-imgerror="defaultImg" class="avatar" :src="userinfo.staffPhoto" alt="">
-------------------------------------
export default {
data() {
return {
// require 解析图片.
defaultImg: require('@/assets/common/head.jpg')
}
}
}