When trying to show a Vue view, there was an issue with reading properties of null, specifically the 'style' property

I am experiencing an issue with a header that has an @click event in the body. Instead of displaying a Vue view upon clicking, I am encountering the following error:

Cannot read properties of null (reading 'style')


Upon researching on Stack Overflow, I learned that this error occurs when

document.getElementById("view")
returns null. This could be due to two reasons:

  1. The script is executing before the document has fully loaded, resulting in the inability to find the view item.
  2. The view item does not exist at all.

Given that there is indeed a view item, it seems like the first reason might be causing the error. However, I am unsure why this happens or how to resolve it.


Below is the code snippet from 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>

Answer №1

When working with the getElementById() method in a class, it is important to follow the correct approach of selecting elements by their ID as highlighted by user @Sfili_81.

In addition, utilizing the $ref attribute can help facilitate this process efficiently.

<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>

Answer №2

If you wish to display a conditional class, refer to the example below: Use the Boolean flag isShowInfo (toggle it if necessary) to control the style of the source block by turning its class on/off.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: AngularJS modal not appearing when utilizing partial for template URLExplanation: The Angular

I am having trouble with a modal in a partial file that is supposed to be loaded into my main view using an ng-include tag. However, the template cannot be found and I do not see it being loaded in the console or network tab. The error message I receive is ...

Storing video blobs in the filesystem using Electron and Node.js

My electron application allows users to record video from their webcam using the MediaRecorder API. After hitting the "stop record" button, I am able to obtain a blob of the recorded video. I am trying to figure out how to convert this blob into a real w ...

Vue: Duplicating a div element with unique input fields upon clicking

I have successfully set up a page where I can dynamically add a div/row of inputs by clicking the link. This feature works smoothly and adds the same div below the current one with all the proper inputs. Additionally, one of the inputs is designed as an a ...

Pause and check for the completion of data loading in mapstate

I have a stored userProfile in the Vuex state in order to access it throughout my project. However, when I try to use it in the created() hook, the profile is not loaded yet during the initial page load. Although the object exists, it does not contain any ...

Issue with resizing a Bootstrap pill containing truncated text

After struggling with this issue for some time, I attempted to use javascript to solve it but have been unsuccessful. The challenge involves a tag list in a table that displays a link when hovered over. Following advice from another member on SO, I managed ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

Searching for a substring within a larger string in JavaScript

I am trying to create a loop in JavaScript (Node.js) that checks if a string contains the "\n" character and then splits the string based on that character. <content>Hello </content><br /> <content>bob </content><br / ...

The issue with Bootstrap Vue is that it fails to render the CSS properly when utilizing cards

Recently, I delved into the world of Bootstrap Vue and wrote the code snippet below: <template> <div> <div> <b-card-group> <b-card border-variant="dark" header="Dark" align="center"> &l ...

Error: Axios header not refreshing automatically in React. User must manually refresh the page

After logging in, I want to update the JWT token in the header before redirecting to the home page. Login.tsx ... const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); const data = new FormData(event.curr ...

How can Chinese characters be transformed into XML/HTML-style numerical entities and converted into Unicode UTF-8 encoding?

I have a situation where I need to change a text that contains both English words and Chinese characters into a format that includes XML/HTML-style numerical entities for the Chinese characters. Here's an example of the original text: Title: 目录. ...

Is there a way to prevent the entire row from being selected when a radio button is clicked in an md-data

Can anyone assist me with an issue I am having with my data table? When I select a radio button, the entire table row is getting selected instead of just the radio button. Below is the code snippet: https://i.sstatic.net/dicwF.png My Expectation: When c ...

What is the method for rearranging the order of Bootstrap 5 columns within nested elements without using hidden duplicates?

This snippet of code is designed to show blocks in different ways on mobile and desktop devices. <div class="col-12 col-sm-6 order-sm-1">TITLE</div> <div class="col-12 col-sm-6 order-sm-0">IMAGE</div> <div cla ...

Is there a way to modify the row quantity when using the "show 10/25/50/100/All entries" feature in Vue JS?

Is there a way to dynamically change the number of rows displayed in a table based on the selection made from a dropdown menu? For example, if 25 is selected, I want to show all 25 rows on the table. The dropdown options include: 10/25/50/100/All and I w ...

Overlapping problem with setInterval

I am currently working on a project that requires the use of both setInterval and setTimeout. I am using setTimeout with dynamic delays passed to it. While elements are not timed out, I have implemented setInterval to print out numbers. Here is the code ...

Achieving the perfect button using a combination of material-ui and styled-components

Utilizing the ToggleButton and ToggleButtonGroup components from material-ui, starting with material-ui's gatsby template. To prevent common material-ui errors with production builds, I am attempting to incorporate styled-components as well. The foll ...

Vue.js HTTP POST request not correctly sending object data

I created a Vue.js App that looks like this var vueCommentApp = new Vue({ el: '#Commentdiv', data: { newComment:{"userCommentID":0,"siteurlID":1,"userId":"","userName":"Guest","commentPageT ...

Sharing specific information with a particular component instance in React using .map

I have set up multiple instances of a child component within a parent component using the following code: render() { return ( {this.state.accounts.map(account => <EachAccount key={account.id} curAccountData={account} /> ...

Obtain the values from controls within the <td> element

I'm experiencing some difficulty creating an array of table cell values because the cells contain controls, not just plain text. $("#tbl_CGT tr").each(function() { var arrayOfThisRow = []; var tableData = $(this).find('td'); if (tab ...

Tips for successfully passing a parameter to the --world-parameters or npm run command for it to be utilized by scripts within the package

Although there are similar questions already asked, I still have a specific scenario that I need help with: In the example I am working on, I am using this repository and I have a script block in my package.json as follows: I want to be able to pass a pa ...

Error with XMLHTTPRequest loading in beforeunload/unload event handlers in iOS 13.4.1 encountered

Currently, I am utilizing XMLHTTPRequest for data posting in JavaScript. Previously, it functioned smoothly on Safari and Chrome browsers up to iOS 13.3.1. However, upon updating to the latest OS version, iOS 13.4.1, an error message stating "XMLHTTPReques ...