AdaKing88
2023-08-23 9cad48db6c56c3e2796a9d6da881817ef13b6eca
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
<template>
    <div ref="editor"></div>
</template>
 
<script>
import { ref, onMounted, watch, nextTick } from 'vue';
import WangEditor from 'wangeditor';
// cookies
import { getToken } from "@/utils/cookies";  // 这是封装好的方法
export default {
    name: 'Wangeditor',
    components: {},
    props: {
        value: {
            type: String,
            default: ""
        }
    },
    emits: ["update:value", 'callback'],
    setup(props, { emit }){
        let html = ref(null)
        // 内容
        let content = ref('');
        // 富文本DOM元素
        const editor = ref(null);
        // 富文本对象
        let editor_instance = null;
        // 生命周期
        onMounted(() => {
            nextTick(() => {
                // 创建富文本对象
                editor_instance = new WangEditor(editor.value);
                // 图片上传配置
                editor_instance.config.uploadImgServer = process.env.VUE_APP_DEV_TARGET + '/upload' // 上传图片的接口地址
                editor_instance.config.uploadFileName = 'files' // formdata中的name属性
                editor_instance.config.uploadImgHeaders = {
                    Token: getToken() // 设置请求头
                }
                editor_instance.config.uploadImgHooks = {
                    // 图片上传并返回结果,但图片插入错误时触发
                    fail: function (xhr, editor, result) {
                        console.log(result)
                    },
                    // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
                    customInsert: function(insertImgFn, result) {
                        // insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
                        insertImgFn(result.data.files_path)
                    }
                }
                // 配置change事件
                Object.assign(editor_instance.config, {
                    onchange(value) {
                        content.value = value;
                        emit("update:value", value);
                    },
                });
                // 创建
                editor_instance.create();
            })
        })
        watch(() => props.value, (newContent, oldContent) => {
            editor_instance.txt.html(newContent);
        })
        return { editor }
    }
}
</script>
<style lang='scss' scoped>
</style>