index.vue
3.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<template>
<div>
<QuillEditor
ref="myQuillEditor"
theme="snow"
v-model:content="content"
:options="data.editorOption"
contentType="html"
@update:content="setValue()"
/>
<!-- 使用自定义图片上传 -->
<input
type="file"
hidden
accept=".jpg,.png"
ref="fileBtn"
@change="handleUpload"
/>
</div>
</template>
<script setup>
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { reactive, onMounted, ref, toRaw, watch } from "vue";
// import { backsite } from '@/api'
const props = defineProps(["value"]);
const emit = defineEmits(["updateValue"]);
const content = ref("");
const myQuillEditor = ref();
// watch(() => props.value, (val) => {
// console.log(toRaw(myQuillEditor.value))
// toRaw(myQuillEditor.value).setHTML(val)
// }, { deep: true })
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: "请输入内容...",
},
});
const imgHandler = (state) => {
if (state) {
fileBtn.value.click();
}
};
const setValue = () => {
const text = toRaw(myQuillEditor.value).getHTML();
emit("updateValue", text);
};
const handleUpload = (e) => {
const files = Array.prototype.slice.call(e.target.files);
console.log(files, "files");
if (!files) {
return;
}
const formdata = new FormData();
formdata.append("file", files[0]);
const quill = toRaw(myQuillEditor.value).getQuill();
const length = quill.getSelection().index;
// 插入图片,res为服务器返回的图片链接地址
quill.insertEmbed(
length,
"image",
"https://img.zcool.cn/community/0159645d5a2f40a80120695c8d54fc.jpg@1280w_1l_2o_100sh.jpg"
);
// 调整光标到最后
quill.setSelection(length + 1);
// backsite.uploadFile(formdata)
// .then(res => {
// if (res.data.url) {
// const quill = toRaw(myQuillEditor.value).getQuill()
// const length = quill.getSelection().index
// // 插入图片,res为服务器返回的图片链接地址
// quill.insertEmbed(length, 'image', res.data.url)
// // 调整光标到最后
// quill.setSelection(length + 1)
// }
// })
};
onMounted(() => {
const quill = toRaw(myQuillEditor.value).getQuill();
if (myQuillEditor.value) {
quill.getModule("toolbar").addHandler("image", imgHandler);
}
toRaw(myQuillEditor.value).setHTML(props.value);
});
</script>
<style scoped lang="scss">
:deep(.ql-editor) {
min-height: 180px;
}
:deep(.ql-formats) {
height: 21px;
line-height: 21px;
}
</style>