介紹css
1:當圖片加載失敗時,給出錯誤提示。git
2:當圖片加載中時,給出加載提示。函數
3:圖片處理模式:等比縮放/裁剪/填充/...flex
經過給圖片綁定load事件與error事件處理函數來判斷圖片加載狀態。當圖片加載完成時會觸發load事件;圖片加載出錯會觸發error事件this
// 樣本 <img src="..." @load=onLoad @error=onError>
經過css屬性 object-fit(https://developer.mozilla.org/zh-CN/docs/Web/CSS/object-fit) 來控制圖片如何適應容器大小。spa
<template> <div class="tm-image" :style="style" @click="onClick"> <img :src="src" :alt="alt" :style="{'object-fit': mode}" @load="onLoad" @error="onError"> <div v-if="this.loading" class="tm-image-load"> <slot name="loading">加載中</slot> </div> <div v-if="this.error" class="tm-image-error"> <slot name="error">加載出錯</slot> </div> </div> </template>
<script> import suffixPx from '../../utils/suffixPx.js'; export default { name: "tm-image", data() { return { loading: true, error: false } }, props: { src: String, alt: String, mode: { // 模式:https://developer.mozilla.org/zh-CN/docs/Web/CSS/object-fit type: String, default: "fill", validator(value) { return ['contain', 'cover', 'fill', 'none', 'scale-down'].includes(value); } }, width: [String, Number], height: [String, Number] }, computed: { style() { return { width: suffixPx(this.width), height: suffixPx(this.height) } } }, methods: { onClick(event) { this.$emit('click', event); // 向父節點傳遞一個自定義事件 }, onLoad(event) { this.loading = false; this.$emit('loading', event); // 向父節點傳遞一個自定義事件 }, onError(event) { this.loading = false; this.error = true; this.$emit('error', event); // 向父節點傳遞一個自定義事件 } } } </script>
<style scoped> .tm-image{ position: relative; overflow: hidden; } .tm-image .tm-image-load, .tm-image .tm-image-error{ position: absolute; top:0; left: 0; width: 100%; height: 100%; background: #f2f2f2; color: #666; display: flex; align-items: center; justify-content: center; } .tm-image img { width: 100%; height: 100%; } </style>
Vue組件:https://gitee.com/whnba/component.net
淘寶天貓粉絲專享優惠券code