- 根据用户行为加载和缓存图片
- 用户交互触发加载与缓存
- 点击加载和缓存:在单文件组件中,可以为某个元素(如按钮)绑定点击事件来触发图片加载。例如,有一个“查看详情”按钮,点击后加载并展示商品的高清图片。同时,将加载后的图片缓存起来,方便用户再次查看时快速显示。
<template>
<div>
<button @click="loadProductImage">查看详情</button>
<img v - if="productImageLoaded" :src="productImageSrc" alt="Product Image">
</div>
</template>
<script setup>
import {
ref } from 'vue';
import axios from 'axios';
const productImageLoaded = ref(false);
const productImageSrc = ref('');
const loadProductImage = async () => {
try {
const response = await axios.get('https://example.com/api/product - high - res - image');
productImageSrc.value = response.data;
productImageLoaded.value = true;
localStorage.setItem('product - high - res - image', response.data);
} catch (error) {
console.error('Error loading image:', error);
}
};
</script>
- **滚动加载和缓存**:对于长列表中的图片(如商品列表、新闻列表等),可以利用滚动事件来加载图片。当列表项进入可视区域时加载图片,并根据用户滚动行为来预测可能需要的图片并提前缓存。可以使用`IntersectionObserver`来检测元素是否进入可视区域。
<template>
<div>
<div v - for="(product, index) in productList" :key="index" class="product - item">
<img v - if="product.imageLoaded" :src="product.imageSrc" alt="Product Image">
</div>
</div>
</template>
<script setup>
import {
ref, onMounted } from 'vue';
import axios from 'axios';
const productList = ref([
{
imageLoaded: false, imageSrc: '' },
]);
const loadProductImages = async () => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const productIndex = productList.value.findIndex((product) => product === entry