【问题标题】:How to fix [Vue warn]: Error in mounted hook: "TypeError: document.getElementById(...) is null" (found in <Root>)?如何修复 [Vue 警告]:挂载钩子中的错误:“TypeError: document.getElementById(...) is null”(在 <Root> 中找到)?
【发布时间】:2020-12-10 23:24:31
【问题描述】:

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

如果accepted = true,我想隐藏一些 HTML 元素。 我试图通过 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()
     }

【问题讨论】:

  • this.newContract.accepted = true 始终为真。使用if ( this.newContract.accepted )。 --- 使用 `
    ` 并移除 changeAGBView 方法。但是,如果有人接受了 AGB,为什么要隐藏该复选框。作为客户,如果我的确认消失并且我永远不会像复选框那样回来,我会立即退出页面。 ;-)

标签: javascript forms vue.js dom checkbox


【解决方案1】:

你为什么不直接使用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 包装在该元素中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 2021-03-07
    • 2022-01-03
    • 2020-07-03
    • 2021-04-23
    • 2014-10-13
    • 2012-12-02
    • 2021-03-28
    相关资源
    最近更新 更多