| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162 |
- <script>
- export default {
- name: 'AutoImage',
- props: {
- src: {
- type: String,
- default: null
- },
- placeholder: {
- type: String,
- default: null
- },
- broken: {
- type: String,
- default: 'image-broken'
- },
- retry: {
- type: [Boolean, String],
- default: false
- }
- },
- data () {
- return {
- status: 0
- }
- },
- watch: {
- src: {
- handler (val) {
- if (val) {
- this.load()
- } else {
- this.setStatus()
- }
- },
- immediate: true
- }
- },
- beforeDestroy () {
- this.setStatus()
- },
- methods: {
- load () {
- this.setStatus(1)
- const img = new Image()
- img.onload = () => {
- this.setStatus(2)
- }
- img.onerror = () => {
- this.setStatus(3)
- }
- this.$img = img
- img.src = this.src
- },
- setStatus (status = 0) {
- if (this.$img) {
- this.$img.onload = null
- this.$img.onerror = null
- this.$img = null
- }
- this.status = status
- },
- createPlacehoder (h, val) {
- return h('div', {
- staticClass: 'l-flex--row center o-error-image'
- }, [
- this.createSvgIcon(h, val)
- ])
- },
- createSvgIcon (h, icon) {
- return h('svg-icon', {
- staticClass: 'o-error-image__img',
- props: {
- 'icon-class': icon
- }
- })
- }
- },
- render (h) {
- switch (this.status) {
- case 1:
- return h('div', {
- staticClass: 'l-flex--row center o-error-image'
- }, [
- h('i', {
- staticClass: 'el-icon-loading'
- })
- ])
- case 2:
- return h('img', {
- staticClass: 'o-image',
- attrs: {
- src: this.src
- }
- })
- case 3:
- return this.retry
- ? h('div', {
- staticClass: 'o-error-image retry',
- on: {
- click: $event => {
- $event.stopPropagation()
- this.load()
- }
- }
- }, [
- this.createSvgIcon(h, this.broken),
- h('i', {
- staticClass: 'o-error-image__refresh el-icon-refresh'
- })
- ])
- : this.createPlacehoder(h, this.broken)
- default:
- return this.placeholder ? this.createPlacehoder(h, this.placeholder) : null
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- .o-image {
- object-fit: contain;
- }
- .o-error-image {
- position: relative;
- overflow: hidden;
- &__img {
- width: 100%;
- height: 100%;
- }
- &.retry:hover {
- border-radius: $radius;
- cursor: pointer;
- &::before {
- content: "";
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: rgba(#000, 0.5);
- }
- .o-error-image__refresh {
- display: inline-block;
- }
- }
- &__refresh {
- display: none;
- position: absolute;
- top: 50%;
- left: 50%;
- color: #fff;
- transform: translate(-50%, -50%);
- }
- }
- </style>
|