1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > vue中使用富文本编辑器

vue中使用富文本编辑器

时间:2021-03-01 22:29:19

相关推荐

vue中使用富文本编辑器

vue中使用富文本编辑器

前端开发过程中,会遇到在页面上加入富文本编辑器,在vue项目中开发遇到这一需求的时候,我们可以使用富文本编辑器vue-quill-editor,话不多说,先上一张效果图:

1.安装 vue-quill-editor 依赖

npm install vue-quill-editor --save

2.入口文件main.js中引入

//引入富文本编辑器import VueQuillEditor from 'vue-quill-editor'import 'quill/dist/quill.core.css'import 'quill/dist/quill.snow.css'import 'quill/dist/quill.bubble.css'//注册全局Vue.use(VueQuillEditor);

3.具体使用

html片段:

<!-- 图片上传组件辅助--><el-uploadclass="avatar-uploader"action="http://localhost:"//自定义的图片上传路径name="file":show-file-list="false":on-success="uploadSuccess":on-error="uploadError":before-upload="beforeUpload"id="quill-upload"></el-upload><!--富文本编辑器组件--><el-row v-loading="quillUpdateImg"><quill-editorv-model="ruleForm.cardInfo"ref="myQuillEditor":options="editorOption"@change="onEditorChange($event)"@ready="onEditorReady($event)"></quill-editor></el-row>

script片段:

因为富文本编辑器的图片上传会自动生成base64的字符串(太长了),所有我们自动重写图片上传,重写之后就需要自己声明工具栏

//富文本编辑器工具栏const toolbarOptions = [['bold', 'italic', 'underline', 'strike'], // toggled buttons//['blockquote', 'code-block'], //引用,代码块[{'header': 1}, {'header': 2}], // custom button values[{'list': 'ordered'}, {'list': 'bullet'}],[{'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': []}],[ 'image'],['clean']]

data(){return{editorOption: {placeholder: '请输入文章内容'},quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画,刚开始是false,不显示editorOption: {placeholder: '',theme: 'snow', modules: {toolbar: {container: toolbarOptions, // 工具栏handlers: {'image': function (value) {if (value) {document.querySelector('#quill-upload input').click()} else {this.quill.format('image', false);}}}}}}}},methods:{onEditorChange({editor,html,text}) {//获取文本值// html带html标签//text只有文字},// 上传图片前beforeUpload(res, file) {this.quillUpdateImg = true},// 上传图片成功uploadSuccess(res, file) {// res为图片服务器返回的数据// 获取富文本组件实例let quill = this.$refs.myQuillEditor.quill// 如果上传成功//console.log('chenggong',res)if (res.code == 200 && res.target !== null) {// 获取光标所在位置let length = quill.getSelection().index;// 插入图片 res.info为服务器返回的图片地址// console.info(res.target)// console.info("image",'image')// console.info('length',length)quill.insertEmbed(length, 'image', res.target)// 调整光标到最后quill.setSelection(length + 1)} else {this.$message.error('图片插入失败')}// loading动画消失this.quillUpdateImg = false},// 上传图片失败uploadError(res, file) {// loading动画消失this.quillUpdateImg = falsethis.$message.error('图片插入失败')},onEditorReady(){},getContent(value){}}

就这样,在我们的项目中就添加好了一个富文本编辑框

更多api也可参照其文档,文档链/docs/quickstart/。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。