我有两个用于编辑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 = true
,showTextEditor = false
给了我错误:无法将属性“innerHtml”设置为空,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 = false
,showTextEditor = true
的布尔起始值结果
文本显示在文本编辑器中,没有错误。
结论
我有一种感觉,这与我的
v-if
有关,当showtexteditor设置为false然后更改为true时,也许我们正在尝试在创建新dom之前将文本放入?不太清楚为什么以及如何解决这个问题。 最佳答案
此时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)
}
}
关于javascript - 无法将属性'innerHTML'设置为null”,Vue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54305528/