在 vue2 中使用 wangEditor 时如何实现只保存换行的功能?
时间: 2024-12-10 08:52:22 浏览: 33
在 Vue2 中使用 WangEditor 实现只保存换行功能,你需要对编辑器的内容做特定处理。当用户提交内容时,你可以通过监听 `contentChange` 事件或者直接操作编辑器的富文本数据,过滤掉所有非换行符的内容。下面是一个简单的步骤示例:
1. 首先,在组件中安装并初始化 WangEditor:
```javascript
import WangEditor from 'wangEditor';
export default {
components: {
WangEditorInstance: {
props: ['value'],
template: '<div ref="editor"></div>',
mounted() {
this.editor = new WangEditor(this.$refs.editor)
this.editor.config.menus = [] // 禁用菜单
this.editor.customConfig.onContentChange = (html) => {
// 这里将处理后的HTML返回给父组件
this.$emit('input', html.replace(/<[^>]*>/g, '')); // 只保留换行符
};
this.editor.create();
},
watch: {
value(newVal) {
if (newVal) {
this.editor.txt.html(newVal); // 设置初始内容
} else {
this.editor.txt.clear(); // 清空内容
}
},
},
beforeDestroy() {
this.editor.destroy(); // 销毁编辑器
},
},
},
};
```
2. 使用组件时,提供初始值,并监听 `input` 事件获取处理过的富文本:
```html
<template>
<div>
<WangEditorInstance v-model="content" @input="handleContentChange"></WangEditorInstance>
</div>
</template>
<script>
data() {
return {
content: '',
};
},
methods: {
handleContentChange(html) {
console.log('新内容:', html); // 在这里可以进一步处理或存储
},
}
</script>
```
在这个例子中,`replace(/<[^>]*>/g, '')` 正则表达式会移除所有的 HTML 标签,仅保留换行符。如果需要允许某些特定标签存在,可以根据需求调整正则。
阅读全文
相关推荐
















