image的事件onerror问题?

<template>

<img :src="src" :style="imageStyle" :onerror="onError">

</template>

<script lang="ts">

import { defineComponent } from '@vue/composition-api'

import { string } from 'vue-types'

export default defineComponent({

name: 'ApplicationIcon',

props: {

src: string().def('').isRequired,

defaultImage: string().def('').isRequired

},

setup (props, { emit }) {

const imageStyle = {

backgroundRepeat: 'no-repeat',

backgroundSize: 'contain'

}

// 图片加载失败回调

const onError = () => {

loading.value = false

isLoadError.value = true

// 如何拿到绑定的image对象

// image.src = props.defaultImage

// image.onerror = null

}

return {

imageStyle,

onError

}

}

})

</script>

<style lang="scss" scoped>

</style>

如代码,我想使用img标签和onerror方法使得图片加载失败的时候可以有默认图片,但是我在onerror方法中拿不到image对象,请问我该怎么做?


回答:

<template>

<img ref="imageRef" :src="src" :style="imageStyle" @error="onError">

</template>

<script lang="ts">

import { defineComponent, ref } from '@vue/composition-api'

import { string } from 'vue-types'

export default defineComponent({

name: 'ApplicationIcon',

props: {

src: string().def('').isRequired,

defaultImage: string().def('').isRequired

},

setup (props) {

const imageRef = ref(null)

const imageStyle = {

backgroundRepeat: 'no-repeat',

backgroundSize: 'contain'

}

// 图片加载失败回调

const onError = () => {

if (imageRef.value) {

imageRef.value.src = props.defaultImage

imageRef.value.onerror = null

}

}

return {

imageRef,

imageStyle,

onError

}

}

})

</script>


回答:

事件对象event里有

const onError = event => {

// dosomething

}

https://developer.mozilla.org/en-US/docs/Web/API/Event/target

顺便补充下,加载失败的默认图片不止有js一种方法,你也可以考虑CSS,参考下这篇
https://segmentfault.com/a/1190000016855234

以上是 image的事件onerror问题? 的全部内容, 来源链接: utcz.com/p/934329.html

回到顶部