vue富文本组件wangEditor,从父组件中传null值过来时,富文本组件值不更新问题解决

问题描述

点击父组件中左侧表格行时,会传新值到右侧子组件富文本框,但是如果新值为null时,富文本框的旧值不会被清空
在这里插入图片描述

解决方案

利用computed计算属性里的get方法,判断props传过来的值为空时,
返回空标签'<p></p>',这样当父组件传过来的值为空时,组件值也会更新

示例关键代码:

<template>
  <div >
    <Editor v-model="valueHtml" />
  </div>
</template>
<script setup lang="ts">
	const props = defineProps({
	  content: {
	    type: String
	  }
	})
	const valueHtml = computed({
	  get() {
	    if (props.content) {
	      return props.content
	    } else {
	      // 为空值的时候返回这个,要不然富文本组件不会把null值直接更新到页面显示
	      return '<p></p>'
	    }
	  },
	  set(newvalue) {
	    emit('update:content', newvalue)
	  }
	})
</script>
Vue 3中将WangEditor富文本编辑器封装成一个组件,并在调用获取其中的内容,可以通过以下步骤实现: 1. 安装WangEditor:首先需要安装WangEditor库,可以通过npm或yarn进行安装: ```bash npm install @wangeditor/editor --save # 或者 yarn add @wangeditor/editor ``` 2. 创建WangEditor组件:创建一个.vue文件,比如`WangEditor.vue`,然后引入并使用WangEditor: ```vue <template> <div ref="editorContainer" class="w-e-text-container" /> </template> <script> import { ref, onMounted, onBeforeUnmount } from 'vue'; import wangEditor from '@wangeditor/editor'; export default { name: 'WangEditor', props: { value: { type: String, default: '' } }, setup(props, { emit }) { const editorContainer = ref(null); let editor; onMounted(() => { // 初始化编辑器 editor = new wangEditor(editorContainer.value); // 设置编辑器内容 editor.config.onchange = (newHtml) => { emit('update:value', newHtml); }; editor.create(); // 设置组件初始内容 editor.txt.html(props.value); }); onBeforeUnmount(() => { // 销毁编辑器,避免内存泄漏 editor.destroy(); editor = null; }); return { editorContainer }; } }; </script> <style> /* 样式根据需要进行调整 */ .w-e-text-container { height: 300px; /* 或者其他合适的高度 */ } </style> ``` 3. 在父组件中使用WangEditor组件并获取内容: ```vue <template> <wang-editor v-model:value="content" /> <button @click="getContent">获取内容</button> </template> <script> import WangEditor from './WangEditor.vue'; export default { components: { WangEditor }, data() { return { content: '' // 使用v-model绑定内容 }; }, methods: { getContent() { console.log(this.content); // 这里可以获取到编辑器中的内容 } } }; </script> ``` 4. 在子组件中,我们使用了`v-model:value`与父组件进行双向数据绑定,这样父组件可以直接获取到编辑器中的内容。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值