如何修复 [Vue 警告]:挂载钩子中的错误:"TypeError: document.getElementById(...) is null"(在 <Root>中找到)?



我有一个复选框,当用户标记它时,属性为accepted的vue.js数据将从false变为true。

如果accepted = true。我试图通过id获取元素并设置display: none。我得了TypeError: document.getElementById(...) is null。我想这是因为我的函数是在页面完全加载之前执行的。

我该怎么修?

谢谢

HTML

<div id="acceptedTrue" >
<form action="" class="AGBcheckbox" >
<input
id="checkbox"
onkeyup="agbValidate('checkbox')"
v-model="newContract.accepted"
class="AGBcheckboxInput"
type="checkbox"
name="AGB"
value="AGB"
/>
<label for="AGB">
I agree the terms and conditions
</label>
</form>
</div>

vue.js

new Vue({
el: "#app",
delimiters: ["[[", "]]"],
data() {
return {
newContract: {
postcode: "",
accepted: false,
accepted_by: "",
},
};
},
methods: {
changeAGBview() {         
if(this.newContract.accepted = true)  {
document.getElementById("acceptedTrue").style.display = "none"
}
}
},
mounted() {
this.changeAGBview()
}

为什么不直接使用v-if:

<div id="acceptedTrue" v-if="!newContract.accepted">
<form action="" class="AGBcheckbox" >
<input
id="checkbox"
onkeyup="agbValidate('checkbox')"
v-model="newContract.accepted"
class="AGBcheckboxInput"
type="checkbox"
name="AGB"
value="AGB"
/>
<label for="AGB">
I agree the terms and conditions
</label>
</form>
</div>

顺便说一句,由于您的新Vue实例已附加到id为#app的元素,请确保将html封装在该元素中。

最新更新