需要在一个vue-iview项目中引入一个轻量级富文本,并且结合iview的upload钩子函数实现自定义图片上传token验证
将图片先上传至服务器,再将图片链接插入到富文本中
图片上传的话可以使用element或者iview,这里我以iview举例
图片上传区域要隐藏,自定义vue-quill-editor的图片上传,点击图片上传时调用iview或者element的图片上传,
上传成功后在富文本编辑器中显示图片
npm install vue-quill-editor --save
main.js
import VueQuillEditor from 'vue-quill-editor'
Vue.use(VueQuillEditor);
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
html:
<quill-editor
v-model="content"
:options="editorOption"
ref="QuillEditor">
</quill-editor>
js:
<script>
// 工具栏配置
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{'header': 1}, {'header': 2}], // custom button values
[{'list': 'ordered'}, {'list': 'bullet'}],
[{'script': 'sub'}, {'script': 'super'}], // superscript/subscript
[{'indent': '-1'}, {'indent': '+1'}], // outdent/indent
[{'direction': 'rtl'}], // text direction
[{'size': ['small', false, 'large', 'huge']}], // custom dropdown
[{'header': [1, 2, 3, 4, 5, 6, false]}],
[{'color': []}, {'background': []}], // dropdown with defaults from theme
[{'font': []}],
[{'align': []}],
['link', 'image', 'video'],
['clean'] // remove formatting button
]
export default {
data () {
return {
content: '',
editorOption: {
modules: {
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
'image': function (value) {
if (value) {
alert('自定义图片')
} else {
this.quill.format('image', false);
}
}
}
}
}
}
}
}
}
</script>
html:
<Upload
:show-upload-list="false"
:on-success="handleSuccess"
:format="['jpg','jpeg','png','gif']"
:max-size="2048"
multiple
action="/file/upload"
>
<Button icon="ios-cloud-upload-outline" ></Button>
</Upload>
<quill-editor
v-model="content"
:options="editorOption"
ref="QuillEditor">
</quill-editor>
css:
.ivu-upload {
display: none;
}
js:
data () {
return {
content: '',
editorOption: {
modules: {
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
'image': function (value) {
if (value) {
// 调用iview图片上传
document.querySelector('.ivu-upload .ivu-btn').click()
} else {
this.quill.format('image', false);
}
}
}
}
}
}
}
},
methods: {
handleSuccess (res) {
// 获取富文本组件实例
let quill = this.$refs.QuillEditor.quill
// 如果token验证成功,则上传成功
if (res) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(length, 'image', res)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
// 提示信息,需引入Message
Message.error('图片插入失败')
}
},
}