vue3中lazy函数
在 Vue 3 中,lazy 并不是一个内置函数,但可以通过一些技巧实现类似 懒加载(Lazy Loading) 的功能。懒加载通常用于延迟加载资源(如组件、图片、数据等),以提升应用的性能和用户体验。
以下是 Vue 3 中实现懒加载的几种常见方法。
- 懒加载组件
Vue 3 提供了 defineAsyncComponent 函数,用于异步加载组件,从而实现组件的懒加载。
import { defineAsyncComponent } from 'vue';
// 使用 defineAsyncComponent 懒加载组件
const LazyComponent = defineAsyncComponent(() =>
import('./LazyComponent.vue')
);
export default {
components: {
LazyComponent,
},
};
在模板中使用:
<template>
<div>
<LazyComponent v-if="showComponent" />
<button @click="showComponent = true">Load Component</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const showComponent = ref(false);
</script>
- 懒加载图片
可以通过 IntersectionObserver 或 loading="lazy" 属性实现图片的懒加载。
使用 loading="lazy"(原生支持)
<template>
<img src="image.jpg" loading="lazy" alt="Lazy Image" />
</template>
使用 IntersectionObserver
<template>
<img :src="imageSrc" ref="image" alt="Lazy Image" />
</template>
<script setup>
import { ref, onMounted } from 'vue';
const imageSrc = ref('');
const image = ref(null);
onMounted(() => {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
imageSrc.value = 'image.jpg'; // 加载图片
observer.unobserve(entry.target); // 停止观察
}
});
});
observer.observe(image.value); // 开始观察图片元素
});
</script>
- 懒加载数据
可以通过 onMounted 或 watch 实现数据的懒加载。
<template>
<div>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="loadData">Load Data</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([]);
const loadData = async () => {
const response = await fetch('https://api.example.com/data');
items.value = await response.json();
};
</script>
- 懒加载路由
Vue Router 支持懒加载路由,通过动态导入组件实现。
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/lazy',
component: () => import('./LazyComponent.vue'), // 懒加载组件
},
],
});
export default router;
- 自定义
lazy函数
如果需要更灵活的懒加载逻辑,可以自定义一个 lazy 函数。
function lazy(loader) {
let loaded = false;
let result = null;
return () => {
if (!loaded) {
loaded = true;
result = loader();
}
return result;
};
}
// 使用自定义 lazy 函数
const lazyComponent = lazy(() => import('./LazyComponent.vue'));
export default {
components: {
LazyComponent: lazyComponent,
},
};
总结
在 Vue 3 中,可以通过以下方式实现懒加载:
-
组件懒加载:使用
defineAsyncComponent。 -
图片懒加载:使用
loading="lazy"或IntersectionObserver。 -
数据懒加载:通过
onMounted或watch实现。 -
路由懒加载:使用 Vue Router 的动态导入。
-
自定义
lazy函数:实现更灵活的懒加载逻辑。
懒加载可以有效提升应用的性能,特别是在资源较多或网络较慢的情况下。
更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github