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:
- The script is running before the document has been loaded and thus no
view
item can be found. - 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
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.Why don’t you use conditional class like below source???