<template>
    <view class="hc-img-view" :style="{'width':widths,'height':heights,'aspect-ratio':aspectRatio,'background-image':srcs}">
        <image class="image-bar" :src="url" @error="imgError" @load="imgLoad"/>
        <view class="bg-gray-1 hc-flex-center h-full radius" v-if="!isImage">
            <view class="p-1 text-gray-4">
                <view class="text-40 text-center">
                    <text class="i-ri-emotion-sad-line"/>
                </view>
                <view class="text-22">加载失败</view>
            </view>
        </view>
    </view>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
const props = defineProps({
    'src': String,
    'width': [String, Number],
    'height': [String, Number]
});
//初始变量
const srcs = ref('');
const widths = ref('');
const heights = ref('');
const aspectRatio = ref('');

//图片Url
const url = ref(props.src);
const isImage = ref(true)

//加载完成
onMounted(() => {
    setStyleData(props.width, props.height);
});

//监听变化
watch(() => [
    props.src,
    props.width,
    props.height
], ([src, width, height]) => {
    url.value = src;
    setStyleData(width, height);
})

//设置样式
const setStyleData = (width, height) => {
    widths.value = (width * 2) + 'rpx';
    heights.value = (height * 2) + 'rpx';
    aspectRatio.value = 'auto ' + width + ' / ' + height;
}

//图片加载失败
const imgError = () => {
    srcs.value = '';
    isImage.value = false
}
//图片载入完毕
const imgLoad = () => {
    srcs.value = `url(${url.value})`;
    isImage.value = true
}
</script>

<style lang="scss" scoped>
.hc-img-view {
    background-position: 0% 0%;
    background-size: 100% 100%;
    display: inline-block;
    .image-bar {
        position: absolute;
        width: 0;
        height: 0;
        will-change: transform
    }
}
</style>
