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对象,请问我该怎么做?

阅读 2.1k
2 个回答
<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>
推荐问题
logo
Microsoft
子站问答
访问
宣传栏