# 1.0.4 配置文档

[返回1.0.4目录](./api.md) | [返回主文档](../../README.md)

## ⚙️ 富文本
### quick-start

### 添加一个处理富文本中图片URL的辅助函数，并修改watch 监听确保回显时图片URL正确
```javascript
<!--/src/components/Editor/index.vue-->

// 如果需要处理富文本中已有的图片URL（编辑回显时）
const processImageUrls = (htmlContent) => {
    if (!htmlContent) return htmlContent;

    // 创建一个临时div来解析HTML
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlContent;

    // 查找所有的img标签
    const images = tempDiv.getElementsByTagName('img');

    for (let img of images) {
        const src = img.getAttribute('src');

        // 如果src是相对路径且不是完整URL，可能需要转换
        if (src && !src.startsWith('http://') && !src.startsWith('https://') && !src.startsWith('data:')) {
            // 这里可以根据需要决定是否转换为完整URL
            // 例如：img.src = baseUrl.value + src;
        }
    }

    return tempDiv.innerHTML;
};

// 然后在watch中使用
watch(() => props.value, (val) => {
    if (val) {
        // 处理图片URL
        content.value = processImageUrls(val);
    } else {
        content.value = '';
    }
    toRaw(myQuillEditor.value)
}, { deep: true });

```

### 修改文件上传的响应处理，添加错误处理
```javascript
<!--/src/components/Editor/index.vue-->

const handleUpload = (e) => {
    const files = Array.prototype.slice.call(e.target.files)
    if (!files || files.length === 0) {
        return
    }

    const file = files[0];

    // 可以在这里添加文件类型和大小验证
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!validTypes.includes(file.type)) {
        console.error('请上传jpg、png或gif格式的图片');
        e.target.value = '';
        return;
    }

    if (file.size > maxSize) {
        console.error('图片大小不能超过5MB');
        e.target.value = '';
        return;
    }

    const formdata = new FormData()
    formdata.append('file', file)

    download.post("/common/upload", formdata).then(res => {
        if (res.code === 200) {
            const quill = toRaw(myQuillEditor.value).getQuill()
            const length = quill.getSelection().index

            // 关键修改：优先使用 ossUrl，如果没有则使用 url
            const imageUrl = res.ossUrl || res.url || res.fileName;

            // 插入图片
            quill.insertEmbed(length, 'image', imageUrl)

            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
            console.error('上传失败:', res.msg);
        }
    }).catch(error => {
        console.error('上传请求失败:', error);
    }).finally(() => {
        // 清空文件输入
        e.target.value = ''
    })
}

```
## 整体果蔬案例
### 组件
```vue
<!--/src/components/Editor-->
<!--   npm install @vueup/vue-quill@1.2.0 -->
<template>
  <div>
    <QuillEditor :enable="false"  ref="myQuillEditor" theme="snow" v-model:content="content" :options="data.editorOption"
      contentType="html" @update:content="setValue()" />
    <!-- 使用自定义图片上传 -->
    <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
  </div>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import download from '@/utils/request'


const props = defineProps(['value'])
const emit = defineEmits(['updateValue'])
const content = ref('')
const myQuillEditor = ref()

const fileBtn = ref()
const baseUrl = ref(import.meta.env.VITE_APP_BASE_API)
const data = reactive({
  /* content: '', */
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'header': 1 }, { 'header': 2 }],
        ['image'],
        [{ 'direction': 'ltr' }],
        [{ 'color': [] }, { 'background': [] }]
      ]
    },
    placeholder: '请输入内容...'
  }
})
// 然后在watch中使用
watch(() => props.value, (val) => {
  if (val) {
    // 处理图片URL
    content.value = processImageUrls(val);
  } else {
    content.value = '';
  }
  toRaw(myQuillEditor.value)
}, { deep: true });

// 如果需要处理富文本中已有的图片URL（编辑回显时）
const processImageUrls = (htmlContent) => {
  if (!htmlContent) return htmlContent;

  // 创建一个临时div来解析HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = htmlContent;

  // 查找所有的img标签
  const images = tempDiv.getElementsByTagName('img');

  for (let img of images) {
    const src = img.getAttribute('src');

    // 如果src是相对路径且不是完整URL，可能需要转换
    if (src && !src.startsWith('http://') && !src.startsWith('https://') && !src.startsWith('data:')) {
      // 这里可以根据需要决定是否转换为完整URL
      // 例如：img.src = baseUrl.value + src;
    }
  }

  return tempDiv.innerHTML;
};

const setValue = () => {
  const text = toRaw(myQuillEditor.value).getHTML()
  emit('updateValue', text)
}

const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click()
  }
}
const handleUpload = (e) => {
  const files = Array.prototype.slice.call(e.target.files)
  if (!files || files.length === 0) {
    return
  }

  const file = files[0];

  // 可以在这里添加文件类型和大小验证
  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  const maxSize = 5 * 1024 * 1024; // 5MB

  if (!validTypes.includes(file.type)) {
    console.error('请上传jpg、png或gif格式的图片');
    e.target.value = '';
    return;
  }

  if (file.size > maxSize) {
    console.error('图片大小不能超过5MB');
    e.target.value = '';
    return;
  }

  const formdata = new FormData()
  formdata.append('file', file)

  download.post("/common/upload", formdata).then(res => {
    if (res.code === 200) {
      const quill = toRaw(myQuillEditor.value).getQuill()
      const length = quill.getSelection().index

      // 关键修改：优先使用 ossUrl，如果没有则使用 url
      const imageUrl = res.ossUrl || res.url || res.fileName;

      // 插入图片
      quill.insertEmbed(length, 'image', imageUrl)

      // 调整光标到最后
      quill.setSelection(length + 1)
    } else {
      console.error('上传失败:', res.msg);
    }
  }).catch(error => {
    console.error('上传请求失败:', error);
  }).finally(() => {
    // 清空文件输入
    e.target.value = ''
  })
}
onMounted(() => {
  const quill = toRaw(myQuillEditor.value).getQuill()
  if (myQuillEditor.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
  }
  toRaw(myQuillEditor.value).setHTML(props.value)

})
</script>
<style scoped lang="scss">
:deep(.ql-editor) {
  min-height: 180px;
}

:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>

```
### 使用
```javascript
import Editor from '@/components/Editor'

app.component('Editor', Editor)
```
```vue
 <el-form-item label="图文详情">
    <Editor :value="form.content" @updateValue="getMsg" />
  </el-form-item>
```

## 相关文档
[返回主文档](../../README.md)

*迁移改造若依版本: 1.0.4-SNAPSHOT | 最后更新: 2025-12-05*