Vue + wangEditor 富文本编辑器,初始化时向文本框中插入内容失败

我想要实现一个编辑的操作,进入页面时从后台获取数据后将数据插入富文本框中,
数据请求到了,但用官方的方法 editor.txt.html()没能将数据插入到文本框中去。

下面是截图,还有代码:
红色箭头所指就是我请求到的数据,即想插入文本框中的数据,但是不知道为什么是空的
图片描述

代码

HTML中的代码

  <el-form :model="quizData" ref="testForm">
    <el-form-item label="题干" required>
      <br>
      <div ref="editor" style="text-align:left"></div>
      {{this.quizData.quizTitle}}
    </el-form-item>
 </el-form>

数据请求在create中

created () {
  this.getQuizInfo()

 //getQuizInfo()在methods中
  getQuizInfo () {
    quizInfo().then(res=>{
      this.quizData = res.data
    })
  },
},

quizData的数据结构

 quizData:{
    "quizId": 0,
    quizTitle: "",
    quizType: 0,   
    "updateTime": "2018-11-28T03:10:25.082Z",
},

文本框初始化在mounted中

mounted() {
  var editor = new E(this.$refs.editor)
  editor.customConfig.onchange = (html) =>{
    console.log(html)
    this.quizData.quizTitle = html
  }
  editor.customConfig.menus = [
    'head',  // 标题
  ]
  editor.create()
  editor.txt.html(this.quizData.quizTitle)
},
阅读 12.9k
3 个回答

clipboard.png
此处看样子是服务端获取数据吧,这个东西是异步的。

那么问题就是: create的时候发请求获取数据,mounted的时候直接用数据,那么你怎么能保证mounted的时候,数据已经请求成功了呢? 你的问题应该就是你mounted赋值的时候还是没有数据的,因此无效。

获取数据设置数据应该是一个方法,在mounted时候调用,获取到数据了再赋值。

mounted() {
  var editor = new E(this.$refs.editor)
  editor.customConfig.onchange = (html) =>{
    console.log(html)
    this.quizData.quizTitle = html
  }
  editor.customConfig.menus = [
    'head',  // 标题
  ]
  editor.create()
  this.quizInfo().then(res=>{
     this.quizData = res.data
     editor.txt.html(this.quizData.quizTitle)   
  })  
},

@依韵_宵音 思路方法很正确,还有一种解决办法:

mounted中初始化editor时,使用this.editor,且在此处不做赋值editor.txt.html(this.quizData.quizTitle)

mounted() {
  this.editor = new E(this.$refs.editor)
  this.editor.customConfig.onchange = (html) =>{
    console.log(html)
    this.quizData.quizTitle = html
  }
  this.editor.customConfig.menus = [
    'head',  // 标题
  ]
  this.editor.create()
},

这样的话,在methods中,可以灵活使用使用this.editor的赋值this.editor.txt.html()、清空this.editor.txt.clear()等操作。

//在methods中
  getQuizInfo () {
    quizInfo().then(res=>{
      this.quizData = res.data
      this.editor.txt.html(this.quizData.quizTitle)   
      //或 this.editor.txt.html(this.res.data.quizTitle) 
    })
  },
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题