nuxt vue-quill-editor 上传图片
时间: 2023-10-09 13:05:59 浏览: 124
要在Nuxt中使用vue-quill-editor并上传图片,可以按照以下步骤操作:
1. 安装依赖:
```
npm install vue-quill-editor --save
npm install quill-image-resize-module --save
```
2. 在nuxt.config.js中引入quill-image-resize-module依赖:
```
plugins: [
{
src: "@/plugins/vue-quill-editor",
ssr: false
}
],
```
3. 在plugins文件夹下创建vue-quill-editor.js文件,并在文件中引入vue-quill-editor和quill-image-resize-module:
```
import Vue from 'vue'
import Quill from 'vue-quill-editor/dist/ssr'
import 'quill/dist/quill.snow.css'
if (process.browser) {
const ImageResize = require('quill-image-resize-module').default
Quill.Quill.register('modules/imageResize', ImageResize)
}
Vue.use(Quill)
```
4. 在需要使用vue-quill-editor的组件中引入QuillEditor组件,并在data中定义uploadUrl和headers:
```
<template>
<div>
<quill-editor v-model="content" :options="editorOption" />
</div>
</template>
<script>
import QuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.snow.css'
export default {
components: {
QuillEditor
},
data() {
return {
content: '',
editorOption: {
modules: {
toolbar: [
[{ header: [1, 2, 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'],
['image']
],
imageResize: {},
imageDrop: true,
imageResize: {
displaySize: true
}
},
theme: 'snow'
},
uploadUrl: 'http://localhost:3000/upload', // 上传图片的地址
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
}
}
}
</script>
```
5. 在服务器端创建/upload路由,用于接收上传的图片,并返回图片地址:
```
const express = require('express')
const multer = require('multer')
const router = express.Router()
// 配置multer
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({ storage })
router.post('/upload', upload.single('file'), (req, res) => {
const file = req.file
const url = `http://localhost:3000/uploads/${file.originalname}`
res.json({ code: 200, message: '上传成功', data: { url } })
})
module.exports = router
```
这样就完成了在nuxt中使用vue-quill-editor并上传图片的操作。
阅读全文