场景
业务需求,要对element-ui的el-image组件进行封装,实现悬浮可预览,可删除的操作
开始封装
<template>
<span class="edit-image">
<el-image v-bind="$attrs" ref="image" v-on="$listeners">
<template v-for="(value, name) in $slots" #[name]="slotData">
<slot :name="name" v-bind="slotData || {}"></slot>
</template>
</el-image>
<span class="edit-image-model" v-if="!imageError">
<span class="edit-image-preview" @click="preview"
><i class="el-icon-zoom-in"></i
></span>
<span class="edit-image-delete" @click="remove"
><i class="el-icon-delete"></i
></span>
</span>
</span>
</template>
<script>
export default {
computed:{
imageError(){
return this.$refs.image.error
}
}
};
</script>
遇到的问题
这个遮罩需要在el-image加载成功的时候才出现,这时候就通过ref获取到了组件的error属性,加载失败时这个属性会为true,但是呢结果并没有如我所料,获取到的属性一直为false,然后就问了GPT大佬
哦!原来refs不是响应式的!
解决方案
既然computed不行,那就用watch
mounted() {
this.$watch(
() => this.$refs.image.error,
(newVal) => {
this.imageError = newVal;
}
);
},
这样一番操作之后,终于实现了。