在Vue中嵌入neditor

neditor是一款基于百度ueditor的富文本编辑器,它的本质其实也是ueditor,只是对外观进行了美化,个人感觉效果还不错,有很多其他编辑器都没有的功能。
本文是用Vue-cli进行搭建的。
具体的结构如下:


项目结构.jpg

将neditor下载下来保持到static静态文件中


neditor的目录.jpg

接下来在main.js中引入neditor:

// neditor
import '../static/neditor/neditor.config.js'
import '../static/neditor/neditor.all.min.js'
import '../static/neditor/i18n/zh-cn/zh-cn.js'
import '../static/neditor/neditor.parse.min.js'

然后将编辑器单独写成一个组件:
嵌入编辑器的思想是先写一个编辑器的组件,然后把它嵌到需要的地方,组件的代码如下:

<template>
    <div>
        <div :id="this.id"></div>
    </div>
</template>

<script>
    export default {
        name: 'editor',
        props: ['id','r_content'],
        data() {
            return {
                ue: '', //ueditor实例
                content: '', //编辑器内容
            }
        },
        methods: {
            //初始化编辑器
            initEditor() {
                this.ue = UE.getEditor(this.id, {
                    initialFrameWidth: '100%',
                    initialFrameHeight: '350',
                    scaleEnabled: true,
                })
                //编辑器准备就绪后会触发该事件
                this.ue.addListener('ready',()=>{
                    //设置可以编辑
                    this.ue.setEnabled()
                    this.ue.setContent(this.r_content)
                })
                //编辑器内容修改时
                this.selectionchange()
            },
            
            //编辑器内容修改时
            selectionchange() {
                this.ue.addListener('selectionchange', () => {
                    this.content = this.ue.getContent()
                })
            },

        },

        activated() {
            //初始化编辑器
            this.initEditor()
        },
        deactivated() {
            //销毁编辑器实例,使用textarea代替
            this.ue.destroy()
            //重置编辑器,可用来做多个tab使用同一个编辑器实例
            //this.ue.reset()
            //如果要使用同一个实例,请注释destroy()方法
        },

        computed:{
            // 利用计算属性返回prop里传过来的内容
            revecive:function(){
                return this.r_content
            }
        },

        watch:{
            // !!! 这里需要注意,需要一个watch来实时更新编辑器的内容
            revecive:function(){
                this.ue.setContent(this.r_content)
            }
        }

    }
</script>

<style>

</style>

父组件中调用:

<el-form-item style="padding-top: 15px">
    <div style="line-height:24px;width:88%;">
        <!-- Ueditor编辑器需要一个keep-alive标签 -->
        <keep-alive>
            <editor ref="editor" 
                id="editor" 
                v-bind:r_content="setForm.rich_text">
            </editor>
        </keep-alive>
    </div>  
</el-form-item>
# 读出编辑器内容的方法:
<script>
  import editor from '@/components/editor'
  export default {
      data(){
        return { setForm.rich_text:'',  }
      }
      // 赋值的方法:
      this.setForm.rich_text = this.$refs.editor.content
  }
</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容