imzbf / md-editor-v3

Markdown editor for vue3, developed in jsx and typescript, dark theme、beautify content by prettier、render articles directly、paste or clip the picture and upload it...
https://imzbf.github.io/md-editor-v3
MIT License
1.69k stars 162 forks source link

MdPreview可否加一个图片懒加载功能,目前只能这样实现,不知道有没有更好的实现方法 #706

Closed ghost closed 1 month ago

ghost commented 1 month ago

Describe the issue

<template>
  <MdPreview
      editorId="article-markdown"
      :modelValue="valueText"
      previewTheme="smart-blue"
      :codeFoldable="false"
      :noMermaid="true"
      :codeStyleReverse="false"
      :noKatex="true"
      :sanitize="handleSanitize"
  />
</template>

<script setup>
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';

const props = defineProps({
  modelValue:{
    required: true,
    type: String,
    default: ''
  },
})
const valueText = computed({
  get() {
    return props.modelValue
  },
})

const handleSanitize = (html) => {
  //在服务端变更一次
  if (process.server) {
    const loadingImage = '/loading.gif';
    return html.replace(/<img\s+([^>]*?)src="([^"]+)"([^>]*?)>/gi, (match, beforeSrc, srcValue, afterSrc) => {
      return `<img ${beforeSrc}data-src="${srcValue}"${afterSrc} src="${loadingImage}">`
    })
  }
}

const lazyLoadImages = () => {
  const images = document.querySelectorAll('img[data-src]')
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        const img = entry.target
        img.src = img.getAttribute('data-src') // 将 data-src 替换为 src
        img.removeAttribute('data-src') // 移除 data-src 避免重复加载
        observer.unobserve(img) // 停止观察此图片
      }
    })
  })

  images.forEach((img) => observer.observe(img)) // 观察所有带 data-src 的图片
}

onMounted(async ()=>{
  await nextTick()
  lazyLoadImages()
})

</script>

Procedure version

4.21.0

Reproduction link

No response

imzbf commented 1 month ago

内置的markdown-it-image-figures自带了懒加载图片的入口,你参考它的示例试试,配置内部扩展的方式参考:https://imzbf.github.io/md-editor-v3/zh-CN/docs#%F0%9F%8D%A4%20markdownItPlugins