在vue中封装第三方组-el-image(其他相同)

1.背景:
封装el-image 为 custom-image 组件,所有使用custom-image 展示图片的地方,
图片加载过程中都会统一展示“加载中…”的提示,且当加载出错时,会展示统一的默认图。
下面是一个 custom-image 组件加载过程以及加载出错的效果。
2.储备知识:
a t t r s 和 attrs和 attrslistener
attrs

$attrs包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。

当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),
并且可以通过 v-bind=“$attrs” 传入内部组件——在创建高级别的组件时非常有用。

简单点说就是用过$attrs拿到父组件中的值(除了在props中已声明的)
3.上代码:

<template>
  <div id="MyImage">
    <el-image v-bind="$attrs" v-on="$listeners">
      <div slot="error" class="image-slot">
        <img :src="require('@/assets/images/default-image.png')" alt="图片加载失败.png"/>
      </div>
      <div slot="placeholder" class="placeholder-slot">加载中...</div>
    </el-image>
  </div>
</template>

<script>
export default {
    
    
  name: 'MyImage'
}
</script>

<style scoped lang="scss">
  #MytomImage {
    
    
  .image-slot {
    
    
    text-align: center;
  }

  .placeholder-slot {
    
    
    text-align: center;
  }
}
</style>

然后将这个组件注册为全局组件:

import MyImagefrom "@/components/MyImage"
Vue.component('MyImagefrom', MyImagefrom )

在组建中使用:

<my-image fit="fill" class="icon-img" :src="imgUrl"></my-image>

未出来之前:
在这里插入图片描述

使用了v-bind="$attrs"之后,我们在my-image组件中,也拥有了el-image的几乎所有属性,而且其作用效果和用法,是和我们使用el-image是一样的,也就说我们可以看着el-image的文章去使用my-image。
比如直接在my custom中使用src属性。

问:为什么可以直接使用?

答:其实上面vue中官方文章已经回答了,不过这里可能有点绕。感觉上我们是在my-custom中使用了el-image属性,实际上是反过来的。这个需要慢慢理解一下!

我们在my-custom中声明了src,在el-iamge中使用$attrs进行接受,所以是最终是生效的。

猜你喜欢

转载自blog.csdn.net/qq_42931285/article/details/124359407