vue3中,wangEditor富文本组件的使用——.disable()富文本禁用、toolbarKeys配置菜单、shallowRef()创建实例、.destroy()销毁富文本、内容为html格式

vue3中,wangEditor富文本组件的使用——.disable()富文本禁用、toolbarKeys配置菜单、shallowRef()创建实例、.destroy()销毁富文本、内容为html格式

效果图

在这里插入图片描述

1、页面代码

index.vue

<el-button link size="small" type="primary" @click="compile('write', scope.row)"
                            v-if="typeName == '协同编写'">
                            编写
                        </el-button>
                        <el-button link size="small" type="primary" @click="compile('see', scope.row)"
                            v-if="typeName !== '大纲目录'">
                            查看内容
                        </el-button>



<wangEditor v-if="showWang" :initValue="textInfo.content" :disabled="wangDisabled"
                @getEditorContent="onEditorChange"></wangEditor>


<script lang="ts" setup>
import { ref, inject, onMounted } from 'vue';
    
const showWang = ref(false) 
const wangDisabled = ref(false)
const writeId = ref('')
const textInfo = ref({
    content: ''
})
// 列表数据
const getList = () => {
    post(constant.ieopCollaborate + '/collaborate/directory/list', { collaborateId: directoryId }).then((res) => {
        const { code, data } = res.data
        if (code == '200') {
            tableData.value = data
            if (typeName == '协同编写' || typeName == '多元发布') {
                setTimeout(function () {
                    showWang.value = true
                    wangDisabled.value = true
                    seeContent(tableData.value[0].id)
                }, 200)
            }
        }
    })
}

onMounted(() => {
    getList()
})
// 编写和查看
const compile = (type: any, row: any) => {
    setTimeout(function () {
        showWang.value = true
    }, 200)
    console.log(type, row);
    writeId.value = row.id
    seeContent(row.id)
    if (type == 'see') {
        showWang.value = false
        wangDisabled.value = true
    } else {
        showWang.value = false
        wangDisabled.value = false
    }
}

// 富文本
const onEditorChange = (arr: any, html: any) => {
    textInfo.value.content = html
}

// 保存/编辑内容
const saveContent = () => {
    const params = {
        dirId: writeId.value,
        content: textInfo.value.content,
    }
    const url = isEdit.value ? '/collaborate/directory/content/update' : '/collaborate/directory/content/add'
    post(constant.ieopCollaborate + url, params).then((res) => {
        const { code } = res.data
        if (code == '200') {
            ElMessage.success('保存成功')
            showWang.value = false
            setTimeout(function () {
                showWang.value = true
                seeContent(writeId.value)
            }, 200)
        }
    })
}

// 查看内容
const seeContent = (id: any) => {
    post(constant.ieopCollaborate + '/collaborate/directory/content/getByDirId', { dirId: id }).then((res) => {
        const { code, data } = res.data
        if (code == '200') {
            isEdit.value = data?.content
            textInfo.value.content = data?.content
        }
    })
}
</script>
2、引入组件

src\main.ts

/*富文本编辑器*/
app.component('wangEditor', wangEditor);
import wangEditor from "./components/wangEditor/index.vue";
3、组件代码

src\components\wangEditor\index.vue

<template>
    <div style="border: 1px solid #ccc" id="wangEditor">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="min-height: 100px; overflow-y: hidden; text-align: left;" v-model="valueHtml"
            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from 'axios'
import { inject } from "vue";
const constant = inject('constant')
// 初始值
const props = defineProps({
    initValue: String,
    disabled: {
        type: Boolean,
        default :false,
    },
})
const emits = defineEmits(['getEditorContent'])
let mode = ref('default')
// 编辑器实例,必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
// 模拟 ajax 异步获取内容
onMounted(() => {
    nextTick(() => { // 界面节点更新完以后再修改值。
        valueHtml.value = props.initValue
    })
})
// 工具栏配置
const toolbarConfig = {
    toolbarKeys: [
        // 菜单 key
        'headerSelect',
        'bold', // 加粗
        'italic', // 斜体
        'through', // 删除线
        'underline', // 下划线
        'bulletedList', // 无序列表
        'numberedList', // 有序列表
        'color', // 文字颜色
        'insertLink', // 插入链接
        'fontSize', // 字体大小
        'lineHeight', // 行高
        'uploadImage', // 上传图片
        'delIndent', // 缩进
        'indent', // 增进
        'deleteImage',//删除图片
        'divider', // 分割线
        'insertTable', // 插入表格
        'justifyCenter', // 居中对齐
        'justifyJustify', // 两端对齐
        'justifyLeft', // 左对齐
        'justifyRight', // 右对齐
        'undo', // 撤销
        'redo', // 重做
        'clearStyle', // 清除格式
    ]
}
const editorConfig = {
    placeholder: '请输入内容...', // 配置默认提示
    // readOnly: true,
    MENU_CONF: {                // 配置上传服务器地址
        uploadImage: {
            // 小于该值就插入 base64 格式(而不上传),默认为 0
            base64LimitSize: 5 * 1024, // 5kb
            // 单个文件的最大体积限制,默认为 2M
            // maxFileSize: 1 * 1024 * 1024, // 1M
            // // 最多可上传几个文件,默认为 100
            // maxNumberOfFiles: 5,
            // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
            allowedFileTypes: ['image/*'],
            // 自定义上传
            async customUpload(file, insertFn) { // 文件上传
                const formData = new FormData();
                // let formData = new FormData();
                formData.append('file', file);
                formData.append('fileName', file.name)
                formData.append('fileType', '0')
                formData.append('encrypt', 1)
                formData.append('domain', "wangEditor")
                formData.append('code', '1');               // 业务标记
                formData.append('remark', "");           // 备注
                // 这里根据自己项目封装情况,设置上传地址
                // axios.defaults.headers.common['Authorization'] = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjVhYzc3MDQxLTE3NGItNDEwZC1hOTJlLTVkYzU0YmRhMjllNiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.GhdthjLmw4NP2WV2owYQS70tacRM-pX7NqI7Mo0_j_hatiqtSrqAr0RJC40osRETiQo_dacZcvNqATLsJHL77A'
                let result = await axios.post(process.env.VUE_APP_API_HOST + constant.fileUpload + '/uploadImage', formData)
                // 插入到富文本编辑器中,主意这里的三个参数都是必填的,要不然控制台报错:typeError: Cannot read properties of undefined (reading 'replace')
                insertFn(process.env.VUE_APP_API_HOST + constant.fileUpload + '/previewImage?id=' + result.data.data[0].id, file.name, file.name)
            }
        }
    }
}
// 组件销毁时,也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})
const handleCreated = (editor) => {
    editorRef.value = editor // 创建富文本编辑器
    if(props.disabled){
        editorRef.value.disable()  //禁用
    }
}
const handleChange = (info) => {
    // info.children 数组包含了数据类型和内容,valueHtml.value内容的html格式
    emits('getEditorContent', info.children, valueHtml.value)
}
watch(() => props.initValue, (value) => {  // 父组件获取初始值
    valueHtml.value = value
})
</script>

<style>
.w-e-text-placeholder {
    top: 10px;
}

.w-e-text-container {
    height: 300px;
}

.w-e-selected-image-container {
    max-width: 800px;
}

.w-e-hover-bar .w-e-bar-item:nth-of-type(4),
.w-e-hover-bar .w-e-bar-item:nth-of-type(5) {
    display: none;
}
</style>
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您介绍一下使用Vue3封装WangEditor富文本组件的步骤。 首先,我们需要安装WangEditorVue3,可以通过以下命令进行安装: ```bash npm install wangeditor@latest npm install vue@next ``` 接着,我们可以在Vue3的组件使用WangEditor。下面是一个简单的示例: ```vue <template> <div ref="editorElem"></div> </template> <script> import WangEditor from 'wangeditor' export default { mounted() { const editor = new WangEditor(this.$refs.editorElem) editor.create() } } </script> ``` 在上面的代码,我们通过import导入了WangEditor,并在mounted钩子函数创建了一个新的编辑器实例。注意,我们需要在组件的模板添加一个ref属性,用于引用编辑器的DOM元素。 如果您需要进一步封装WangEditor组件,可以考虑将其封装为一个Vue组件,以便在其他地方重复使用。下面是一个简单的示例: ```vue <template> <div :id="editorId"></div> </template> <script> import WangEditor from 'wangeditor' export default { props: { value: String, placeholder: String, height: { type: String, default: '300px' } }, data() { return { editorId: `editor-${Math.random().toString(36).substr(2, 9)}`, editor: null } }, mounted() { this.editor = new WangEditor(`#${this.editorId}`) this.editor.config.height = this.height this.editor.config.placeholder = this.placeholder this.editor.config.onchange = this.handleChange this.editor.create() this.editor.txt.html(this.value) }, methods: { handleChange() { this.$emit('input', this.editor.txt.html()) } }, beforeUnmount() { this.editor.destroy() } } </script> ``` 在上面的代码,我们定义了一个WangEditor组件,并通过props接收了一些参数,包括组件的初始值、占位符和高度等。在mounted钩子函数,我们创建了一个新的编辑器实例,并通过config属性设置了一些编辑器的配置项,包括高度、占位符和内容变化时的回调函数等。我们还通过handleChange方法监听了编辑器内容的变化,并通过$emit方法向父组件发送了一个input事件,以便在父组件更新组件的绑定值。最后,我们在beforeUnmount钩子函数销毁了编辑器实例,以避免内存泄漏。 使用时,您可以像使用其他自定义组件一样,在Vue3的模板引用WangEditor组件,并通过v-model指令绑定组件的值: ```vue <template> <div> <wangeditor v-model="content" placeholder="请输入内容" height="500px" /> <div>{{ content }}</div> </div> </template> <script> import WangEditor from '@/components/WangEditor.vue' export default { components: { WangEditor }, data() { return { content: '' } } } </script> ``` 在上面的代码,我们通过import导入了WangEditor组件,并在模板引用了该组件。我们还通过v-model指令绑定了组件的值,以便在父组件获取和更新该值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值