[Vue-rx] Handle Image Loading Errors in Vue.js with RxJS and domStreams

本文介绍如何在Vue中处理图片加载失败的情况,通过使用RxJS实现错误处理逻辑,当主图片无法加载时,自动加载备用图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When an image fails to load, it triggers an error event. You can capture the error event and merge it with your image loading stream to provide a backup image when things go wrong. This lesson shows how to load a placeholder image if the main image fails to load.

 

<img> has 'onerror' event to handle image loading error.

<img src="" onerror="someFn()" />

 

Therefore in Vue, we can do:

<img :src="" error="someFn" />

 

With Vue-rx:

<img :src="" v-stream:error="imageError$" />

export default {
  name: 'app',
  domStreams: [ 'imageError$'],
  subscriptions() {}

}

 

<template>
  <section class="section">
    <button class="button" v-stream:click="click$">Click</button>
    <h2>
      {{name$}}
    </h2>
    <img v-stream:error="imageError$" :src="image$" alt="">
  </section>
</template>

<script>
import { from, merge } from 'rxjs';
import { switchMap, pluck, map, mapTo } from 'rxjs/operators';

export default {
  name: 'app',
  domStreams: ['click$', 'imageError$'],
  subscriptions() {

    const person$ = from(
      this.$http.get(
        "https://starwars.egghead.training/people/1"
      )
    ).pipe(
      pluck('data')
    )

    const luke$ = this.click$.pipe(
      switchMap(() => person$)
    )

    const name$ = luke$.pipe(
      pluck('name')
    )

    const loadImage$ = luke$.pipe(
      pluck('image'),
      map(src => `https://starwars.egghead.trainin/${src}` )
    )

    const failImage$ =  this.imageError$
    .pipe(
      mapTo(`http://via.placeholder.com/400x400`)
    )

    const image$ = merge(
      loadImage$,
      failImage$
    )

    return {
      name$,
      image$
    }
  }
};
</script>

 

转载于:https://www.cnblogs.com/Answer1215/p/9326989.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值