首先安装vue-quill-editor
npm install vue-quill-editor --save
在nuxt中引用
- 在plugins中创建nuxt-quill-plugin.js
import Vue from 'vue'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
if (process.browser) {
// 加一个浏览器端判断,只在浏览器端才渲染就不会报错了
const VueQuillEditor = require('vue-quill-editor/dist/ssr')
Vue.use(VueQuillEditor)
}
plugins[
{
src: '~plugins/nuxt-quill-plugin.js',
ssr: false //仅在客户端渲染
}
]
css: ['~/assets/css/base.css',
'~/assets/css/main.css',
'~/assets/css/color-dark.css',
'element-ui/lib/theme-chalk/index.css',
'quill/dist/quill.snow.css',
'quill/dist/quill.bubble.css',
'quill/dist/quill.core.css'
],
build: {
vendor: ['axios',
'element-ui',
'vue-quill-editor',
'vee-validate'
],
plugins: [
new webpack.ProvidePlugin({
'window.Quill': 'quill/dist/quill.js',
'Quill': 'quill/dist/quill.js'
})
],
<template>
<section class="container"
v-loading="isLoading"
element-loading-text="请稍等,图片上传中">
<input class="file" type="file" style="display:none" id="file" ref="input" @change="doUpload">
<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>
import hljs from 'highlight.js' // 语法高亮
import { upload } from '~/assets/js/upload' // 气牛上传封装
export default {
data () {
const self = this
return {
content: "",
isLoading: false,
editorOption: {
placeholder: this.placeholder,
modules: {
toolbar: {
container:['bold', 'italic', 'underline',{'list': 'ordered'}, {'list': 'bullet'}, 'image','code-block'],
},
syntax: {
highlight: text => hljs.highlightAuto(text).value // 语法高亮插件调用
},
}
}
}
},
props: {
placeholder: {
type: String,
default: '输入描述内容'
}
},
mounted() {
this.myQuillEditor.getModule('toolbar').addHandler('image', this.imgHandler) // 更改原有的base64图片上传
},
methods: {
handleRemove (file, fileList) {
console.log(file, fileList)
},
handlePreview (file) {
console.log(file)
},
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)
if(/<span class="ql-cursor">.*<\/span>/.test(html) || this.content == html) return // 不加这行判断,会陷入死循环
this.content = html
this.$emit('ditorContent', html);
this.$emit('ditorContentText', text);
},
imgHandler (handle) {
let inputfile = document.getElementById('file')
inputfile.click()
},
doUpload: async function () {
this.isLoading = true
let file = document.getElementById('file').files[0]
if(file) {
let fileData = await upload(file) // upload封装上传七牛
let fileKey = `/${fileData.key}?${fileData.hash}?${fileData.fsize}?1`;
let fileUrl = process.env.domain + fileKey; // process.env.domain 七牛上传路径
//将url插入到富文本中
if (fileUrl !== null && fileUrl.length > 0) {
//光标位置
let cursorAddRange = this.myQuillEditor.getSelection();
//插入内容
this.myQuillEditor.insertEmbed(cursorAddRange !== null ? cursorAddRange.index : 0, 'image', fileUrl);
//调整光标位置在图片之后
this.myQuillEditor.setSelection(cursorAddRange.index + 1);
} else {
this.$message.error(`image插入失败`);
}
//清空inout内容
document.getElementById('file').value = "";
this.isLoading = false
}else {
}
}
},
}
</script>
import * as qiniu from 'qiniu-js';
import {uuid} from './util';
import {apiGetUploadToken} from '~/service/api/user'; // 获取七牛上传的token
/**
* 获取文件后缀
* @param key2
* @returns {string}
*/
const getFileName = (key2) => {
let pos = key2.lastIndexOf("."); //查找最后一个\的位置
return key2.substring(pos); //截取最后一个\位置到字符长度,也就是截取文件名 houzhui
};
const getUploadToken = () => {
return new Promise(resolve => {
apiGetUploadToken("1","1").then(res=>{
resolve(res.uploadToken);
});
});
};
/**
*
* @param file
* @param token
* @param putExtra
* @param option
* @returns {Promise<*>}
*/
export const upload = (file, token, putExtra = {}, option) => {
return new Promise(async (resolve, reject) => {
const defaultOption = Object.assign({
quality: 0.92,
noCompressIfLarger: true
}, option);
const defaultputExtra = Object.assign({
fname: "",
params: {},
mimeType: []
}, putExtra);
const key = uuid() + getFileName(file.name);
defaultputExtra.params["x:name"] = key.split(".")[0];
const data = await qiniu.compressImage(file, defaultOption);
const token = await getUploadToken();
const observable = qiniu.upload(data.dist, key, token, putExtra, defaultOption);
const observer = {
next() {//上传中
},
error(err) {//错误
reject(err);
console.error(err);
},
complete(res) {//上传完成
resolve(res);
}
};
observable.subscribe(observer); // 上传开始
})
};
网友评论