文章地址:https://juejin.im/post/5e7c767e51882535d637917e
vue-quil-editor是一個(gè)vue的富文本編輯器插件闯参,功能很豐富脑豹,使用起來也很方便。本文就說一下在nuxt中的使用方法。
1怀偷、安裝
npm install vue-quill-editor --save
2宠叼、新建plugins/vue-quill-editor.js
文件
import Vue from 'vue'
import VueQuillEditor from 'vue-quill-editor/dist/ssr'
Vue.use(VueQuillEditor);
3鄙皇、配置nuxt.config.js
module.exports = {
// other config
// ...
// import css files as global style
css: [
'quill/dist/quill.snow.css',
'quill/dist/quill.bubble.css',
'quill/dist/quill.core.css'
],
plugins: [
// other plugins
{
src: '~/plugins/vue-quill-editor',
ssr: false
}
]
}
4芜赌、組件中使用
<template>
<section class="container">
<div class="quill-editor"
:content="content"
@change="onEditorChange($event)"
@blur="onEditorBlur($event)"
@focus="onEditorFocus($event)"
@ready="onEditorReady($event)"
v-quill:myQuillEditor="editorOption">
</div>
</section>
</template>
<script>
export default {
data () {
return {
content: '<p>I am Example</p>',
editorOption: {
// some quill options
modules: {
toolbar: [
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block']
]
}
}
}
},
methods: {
onEditorBlur(editor) {
console.log('editor blur!', editor)
},
onEditorFocus(editor) {
console.log('editor focus!', editor)
},
onEditorReady(editor) {
console.log('editor ready!', editor)
},
onEditorChange({ editor, html, text }) {
console.log('editor change!', editor, html, text)
this.content = html
}
}
}
</script>
<style lang="scss" scoped>
.container {
width: 60%;
margin: 0 auto;
padding: 50px 0;
.quill-editor {
min-height: 200px;
max-height: 400px;
overflow-y: auto;
}
}
</style>
ok,到這里就可以正常使用vue-quill-editor了伴逸,上面的代碼中只寫很少的配置項(xiàng)缠沈,插件本身有很多功能,可以去vue-quill-editor查看错蝴。
富文本都有插入圖片的功能洲愤,vue-quill-editor默認(rèn)的插入圖片是以base64形式插入的,如果圖片過大顷锰,會(huì)使文本內(nèi)容過長柬赐,非常不好,所以我們可以修改默認(rèn)的方式馍惹,使用src的方式插入圖片躺率。
1玛界、在編輯器附近或者頁面任意地方万矾,新增一個(gè)文件上傳輸入框
<input
type="file"
style="display: none;"
id="getFile"
@change="selectContentImg($event)"
accept="image/gif,image/jpeg,image/jpg,image/png"
>
2、修改vue-quill-editor的配置
editorOption: {
// some quill options
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline', 'strike'],
['blockquote', 'code-block'],
['image']
],
handlers: {
'image': function () {
// 意思是使用插入圖片的功能時(shí)候慎框,觸發(fā)文件上傳控件的點(diǎn)擊事件
document.getElementById('getFile').click();
}
}
}
}
}
3良狈、上傳文件
// 選擇圖片之后的處理
selectContentImg(e) {
let file = e.target.files;
if (file.length > 0) {
let data = new FormData();
for (let item of file) {
data.append('files', item)
}
// 可以使用post方法上傳文件到服務(wù)器
// 然后把返回的路徑拼接好插入到內(nèi)容里
uploadFile(data).then(res => {
this.content += `<img src="${res.imgUrl}" alt="內(nèi)容圖片">`;
})
}
}