skip to Main Content

I have a header with an @click in my body. When clicked, a Vue view should be displayed, but instead I get the error:

Cannot read properties of null (reading 'style')


From what I’ve read the error occurs because document.getElementById("view") returns null, which can happen for a couple of reasons:

  1. The script is running before the document has been loaded and thus no view item can be found.
  2. There is no view item.

Since there certainly is a view item, I’m guessing the first reason is causing the error, yet I do not understand why nor how it can be fixed.


The following is the code in my App.vue file:

<template>
  <h1 @click="showInfo()">Header</h1>
  <div class="view" style="display: none">
    <AnotherView />
  </div>
</template>

<style scoped>
.view {
}
</style>

<script>
import AnotherView from "./views/AnotherView.vue";

export default {
  components: { AnotherView },
  methods: {
    showInfo() {
      document.getElementById("view").style.display = "block";
    },
  },
};
</script>

2

Answers


  1. You are consulting a class in getElementById(), the correct thing is to get it by the ID as the user @Sfili_81 mentioned.

    And you should also use $ref to do this treatment.

    <template>
      <h1 @click="showInfo()">Header</h1>
      <div ref="view-ref" class="view" style="display: none">
        <AnotherView />
      </div>
    </template>
    
    <style scoped>
    .view {
    }
    </style>
    
    <script>
    import AnotherView from "./views/AnotherView.vue";
    
    export default {
      components: { AnotherView },
      methods: {
        showInfo() {
          this.$refs.style.display = "block";
        },
      },
    };
    </script>
    
    Login or Signup to reply.
  2. Why don’t you use conditional class like below source???

    <template>
      <h1 @click="showInfo()">Header</h1>
      <div class="view" :class="{ 'block': isShowInfo }">
        <AnotherView />
      </div>
    </template>
    
    <style scoped>
    .view {
      display: none;
      &.block {
        display: block;
      }
    }
    </style>
    
    <script>
    import AnotherView from "./views/AnotherView.vue";
    
    export default {
      components: { AnotherView },
      data () {
        isShowInfo: false,
      },
      methods: {
        showInfo() {
          this.isShowInfo = true
        },
      },
    };
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search