npm install @vueup/vue-quill@alpha --save
在main.js中引入
import { createApp } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
const app = createApp()
app.component('QuillEditor', QuillEditor)
或者在需要的模块中引入
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
export default {
components: {
QuillEditor
}
}
使用
<QuillEditor ref="myQuillEditor"
theme="snow"
v-model="content"
:options="editorOption"
/>
<!-- 使用自定义图片上传 -->
<input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
<script>
import { reactive, toRefs, onMounted, ref, toRaw } from 'vue'
export default {
setup() {
const myQuillEditor = ref()
const fileBtn = ref()
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': 'rtl' }], //文字编辑方向,从左到右还是从右到左
[{ 'color': [] }, { 'background': [] }]
]
},
placeholder: '请输入内容...'
}
})
onMounted(() => {
let quill = toRaw(myQuillEditor.value).getQuill()
if (myQuillEditor.value) {
quill.getModule("toolbar").addHandler("image", imgHandler);
}
})
const imgHandler = (state) => {
if (state) {
fileBtn.value.click()
}
}
const handleUpload = (e) => {
const files = Array.prototype.slice.call(e.target.files);
// console.log(files, "files")
if (!files) {
return
}
let formdata = new FormData();
formdata.append("file", files[0]);
uploadImg(formdata)
.then(res => {
if (res.data.url) {
let quill = toRaw(myQuillEditor.value).getQuill()
let length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(length, "image", res.data.url);
// 调整光标到最后
quill.setSelection(length + 1);
}
})
}
return {
myQuillEditor,
fileBtn,
...toRefs(data),
handleUpload,
imgHandler
}
}
}
</script>