zoukankan      html  css  js  c++  java
  • [Vue-rx] Handle Image Loading Errors in Vue.js with RxJS and domStreams

    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>
  • 相关阅读:
    SQL创建索引
    SQLServer最耗资源时间的SQL语句
    C# Linq删除父级的同时删除子级
    C# 根据类名创建类的实例对象
    C#利用反射实现两个类的对象之间相同属性的值的复制
    linq时间筛选以及list时间筛选
    为什么watch机制不是银弹?
    我们的前端模版引擎更新总结
    小矮人Javascript模块加载器
    Javascript模版引擎简介
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9326989.html
Copyright © 2011-2022 走看看