无法将属性'innerHTML'设置为null”,Vue

时间:2019-01-22 09:55:05

标签: javascript html vue.js vuejs2

我有两个用于编辑JSON对象的组件。我有一个在这两个之间切换的按钮。这是html代码:

<v-btn @click="switchConfigClicked">Switch config</v-btn>
<h4 class="switchButtonInfo">Switch between editor/plain-text</h4>
<v-btn class="switchEditButton" @click="switchEditButtonClicked">Switch Editor</v-btn>
<div class= "editorComponents">
  <div v-if="showEditComponents" class="editor">
    <div v-if="showJsonEditor">
      <JsonEditor is-edit="true" v-model="editedConfig" ></JsonEditor>
    </div>
    <div v-if="showTextEditor">
      <textarea id="myTextArea" cols=75 rows=100></textarea>
    </div>
  </div>

// Javascript代码

switchEditButtonClicked: function(){

  this.showTextEditor = !this.showTextEditor;
  this.showJsonEditor = !this.showJsonEditor;

  if (this.showTextEditor) {

    this.editedConfig = JSON.stringify({"hello":"test"}, undefined, 4);

    document.getElementById('myTextArea').innerHTML = this.editedConfig;

  }
  else{
    //this.editedConfig = JSON.parse(this.edite)
  }

},

showJsonEditor = trueshowTextEditor = false的起始值给我错误:

  

无法将属性'innerHTML'设置为null”,Vue

我尝试设置如下代码

window.onload = function() {
    // all of your code goes in here
    // it runs after the DOM is built
}

没有显示错误,但也没有显示文本。

测试用例

我从switchConfigClicked中注释了这两行:

//this.showTextEditor = !this.showTextEditor;
//this.showJsonEditor = !this.showJsonEditor;

并反转了showJsonEditor = falseshowTextEditor = true的布尔起始值

结果

文本显示在textEditor中,没有错误。

结论

我觉得这与我的v-if有关,当showTextEditor设置为false然后更改为true时,也许我们正在尝试在创建新DOM之前放入文本?不太确定为什么以及如何解决此问题。

2 个答案:

答案 0 :(得分:3)

textarea目前尚不可用/呈现(由v-if推迟),请尝试在Vue.nextTick内进行查询。

  

推迟下一个DOM更新周期后执行的回调。更改一些数据以等待DOM更新后,请立即使用它。

switchEditButtonClicked: function () {
  this.showTextEditor = !this.showTextEditor;
  this.showJsonEditor = !this.showJsonEditor;

  if (this.showTextEditor) {
    this.editedConfig = JSON.stringify({
        "hello": "test"
      }, undefined, 4);

    Vue.nextTick(() => {
      // Or better yet use a `ref`
      document.getElementById('myTextArea').innerHTML = this.editedConfig;
    });

  } else {
    //this.editedConfig = JSON.parse(this.edite)
  }

}

答案 1 :(得分:0)

  

无法将属性'innerHTML'设置为null”,Vue

这意味着document.getElementById('myTextArea').innerHTML行失败,并且问题出在查找上-document.getElementById('myTextArea')不返回任何内容,这澄清了错误消息-ID查找导致null的出现,您尝试设置其中的innerHTML

要做有一个具有myTextArea ID的元素,因此原因是that the element is not present when the JavaScript code runs

这也解释了为什么将代码设置为与window.onload一起运行时不会显示错误-这将使其在页面完全呈现后执行,因此DOM元素将存在并且您会能够获取它。

之所以没有文本,是因为您添加错误的方式。代替.innerHTML you should set the .value property

document.getElementById('myTextArea').value = this.editedConfig;