Vue图片懒加载

安装 vueuse 插件

npm i @vueuse/core

搜索 useIntersectionObserver 方法
javascript 复制代码
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
 
export default {
  setup() {
    const target = ref(null)
    const targetIsVisible = ref(false)
 
    const { stop } = useIntersectionObserver(
      target,
      ([{ isIntersecting }], observerElement) => {
        targetIsVisible.value = isIntersecting
      },
    )
 
    return {
      target,
      targetIsVisible,
    }
  },
}
使用:
main.js:
1、引入方法
javascript 复制代码
// 用来图片懒加载
import { useIntersectionObserver } from "@vueuse/core";
2、提前配置好 自定义指令
javascript 复制代码
// 全局指令
app.directive("img-lazy", {
  mounted(el, binding) {
    console.log(el, binding.value);
    const { stop } = useIntersectionObserver(
      el,
      ([{ isIntersecting }], observerElement) => {
        console.log(isIntersecting);
        if (isIntersecting) {
          el.src = binding.value;
          stop()     //避免性能浪费,视口可见后不再监听
        }
      }
    );
  },
});
html部分:
javascript 复制代码
 <li v-for="item in list" :key="item.id">
	<RouterLink to="/">
		<img alt="" v-img-lazy="item.picture" />
        <p class="name">{{ item.name }}</p>
        <p class="price">&yen;{{ item.price }}</p>
	</RouterLink>
</li>
相关推荐
Brookty15 小时前
HTML基础知识:表格布局、表单数据提交、元素标识与资源相对路径
前端·html
徐小夕15 小时前
开源!我们用知识图谱重构了电子档案,AI 驱动全文智能关联
前端·vue.js·github
不一样的少年_15 小时前
用了这 Skill,前端兄弟都觉得好
前端·后端·ai编程
恋猫de小郭16 小时前
Flutter Native Interop 稳定了,Platform Channel 要退场了
android·前端·flutter
奶油话梅糖16 小时前
容器启停 2.5 毫秒:11 天 1,700 Star 的 Kiri,用一个 900 KB 的 PID 1 干掉了 runc 和 dockerd
前端·人工智能·rust
kyriewen1 天前
编辑弹窗点了取消,列表里的数据怎么还是变了?
前端·javascript·人工智能
Karl_fang1 天前
🥳 再也不用拿起手机抄验证码!我做了一个 Android → Mac 的「验证码接力」工具
前端·macos·ai编程
谭光志1 天前
如何让 AI 高效工作
前端·后端·ai编程
code2cat1 天前
【随笔】MCP长任务:查询已经返回,为什么任务还没有完成
javascript·人工智能·后端·mcp