123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154 |
- <template>
- <image
- class="img-cache"
- :src="resource"
- :mode="mode"
- :lazy-load="lazyLoad"
- :fade-show="fadeShow"
- :webp="webp"
- :show-menu-by-longpress="showMenuByLongpress"
- :style="[style]"
- @tap="fnEvent('click', $event)"
- @error="fnEvent('error', $event)"
- @load="fnEvent('load', $event)"
- >
- </image>
- </template>
- <script>
- import storage from './storage'
- import download from './download'
- import { resolveFile } from './index'
- export default {
- name: 'ImgCache',
- props: {
- src: {
- type: String
- },
- mode: {
- type: String,
- default: 'scaleToFill'
- },
- lazyLoad: {
- type: Boolean,
- default: false
- },
- fadeShow: {
- type: Boolean,
- default: true
- },
- webp: {
- type: Boolean,
- default: false
- },
- showMenuByLongpress: {
- type: Boolean,
- default: false
- },
- dir: {
- type: String,
- default: 'imgcache'
- },
- width: {
- type: [String, Number]
- },
- height: {
- type: [String, Number]
- },
- customStyle: {
- type: Object,
- default: () => ({})
- }
- },
- data() {
- return {
- resource: ''
- }
- },
- computed: {
- style() {
- let style = { willChange: 'transform' }
-
- if ((this.width ?? '') !== '') style.width = this.addUnit(this.width)
- if ((this.height ?? '') !== '') style.height = this.addUnit(this.height)
- return {
- ...style,
- ...this.customStyle
- }
- }
- },
- watch: {
- src: {
- handler: 'init',
- immediate: true
- }
- },
- methods: {
-
- init() {
-
- this.fnCache()
-
-
- this.setSrc()
-
- },
-
- async fnCache() {
- const url = this.src
- if (!/^https?:\/\
- const [select] = storage.select({ url })
- if (select) {
- const path = select.local
- if (await resolveFile(path)) return this.setSrc(path)
- storage.delete(select)
- }
- this.setSrc()
- const local = await download(url, this.dir)
- if (local) storage.insert({ url, local })
- },
-
- fnEvent(emit, event) {
- this.$emit(emit, event)
- },
-
- setSrc(src) {
- this.resource = src || this.src
- },
-
- addUnit(value) {
- value = String(value ?? '')
- return /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value) ? `${value}rpx` : value
- }
- }
- }
- </script>
|