nuxt vue-quill-editor上传图片
时间: 2023-10-09 21:05:59 浏览: 189
在 Nuxt 中使用 vue-quill-editor 实现图片上传可以通过以下步骤实现:
1. 安装 `vue-quill-editor` 和 `quill-image-resize-module`:
```
npm install vue-quill-editor quill-image-resize-module
```
2. 在 `nuxt.config.js` 中引入需要的样式和脚本:
```
head: {
script: [
{
src: 'https://cdn.quilljs.com/1.3.6/quill.js'
},
{
src: 'https://cdn.quilljs.com/1.3.6/quill.min.js'
}
],
link: [
{
rel: 'stylesheet',
type: 'text/css',
href: 'https://cdn.quilljs.com/1.3.6/quill.snow.css'
}
]
}
```
3. 在需要使用编辑器的组件中引入 `vue-quill-editor` 和 `quill-image-resize-module`:
```vue
<template>
<div>
<quill-editor
ref="myQuillEditor"
v-model="content"
:options="editorOption"
@image-added="onImageAdded"
/>
</div>
</template>
<script>
import { quillEditor, Quill } from 'vue-quill-editor'
import ImageResize from 'quill-image-resize-module'
export default {
components: {
quillEditor
},
data() {
return {
content: '',
editorOption: {}
}
},
mounted() {
// 注册图片大小调整模块
Quill.register('modules/imageResize', ImageResize)
this.editorOption = {
modules: {
toolbar: [
// 工具栏配置
[{ header: [1, 2, 3, false] }],
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
[{ list: 'ordered' }, { list: 'bullet' }],
[{ script: 'sub' }, { script: 'super' }],
[{ indent: '-1' }, { indent: '+1' }],
[{ direction: 'rtl' }],
[{ size: ['small', false, 'large', 'huge'] }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ color: [] }, { background: [] }],
[{ font: [] }],
[{ align: [] }],
['clean'],
['link', 'image', 'video']
],
imageResize: {
displaySize: true
}
}
}
},
methods: {
onImageAdded($event) {
// 图片上传
const file = $event.file
const formData = new FormData()
formData.append('file', file)
axios.post('/api/upload', formData).then(res => {
const imageUrl = res.data.url
const quillEditor = this.$refs.myQuillEditor.quill
const range = quillEditor.getSelection(true)
quillEditor.insertEmbed(range.index, 'image', imageUrl)
quillEditor.setSelection(range.index + 1)
})
}
}
}
</script>
```
4. 通过 `@image-added` 事件监听图片上传,上传完成后,通过 `quillEditor.insertEmbed` 插入图片。
以上就是在 Nuxt 中使用 vue-quill-editor 实现图片上传的步骤。
阅读全文