Home > Mobile >  Vue 3 Composition API - TypeError: Cannot read properties of null (reading 'style')
Vue 3 Composition API - TypeError: Cannot read properties of null (reading 'style')

Time:04-07

I am currently learning Vue 3 composition api and using template refs to access the DOM element and learning to set texts and styles inside using script setup.

Here, I am trying to style the title in <h1> element and set it to a background of red inside the onMounted() hook.

But I am receiving TypeError: Cannot read properties of null (reading 'style') and it seems that it does not work when I set title.value.classList.contains(".title").style.backgroundColor = "red";.

Can anyone tell me what is wrong with my code?

<template>
  <h1 ref="title" ></h1>
  <div  ref="image">
    <img src="https://source.unsplash.com/random" />
  </div>
</template>

<script setup lang="ts">
import Hammer from "hammerjs";
import { ref, onMounted } from "vue";

const title = ref(null);

onMounted(() => {
  title.value.innerText = 'This is an image title';
  title.value.classList.contains(".title").style.backgroundColor = "red";

})

</script>

<style>
.imageContainer {
  width: 96%;
  height: 96%;
  max-width: 800px;
  max-height: 600px;
  position: absolute;
  overflow: hidden;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background: #2b2b2c;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
</style>

CodePudding user response:

ClassList.contains returns a boolean value.

you can see more documentation here

i think what you might be trying to do is

title.value.style.backgroundColor = "red";

CodePudding user response:

I did not use TS for reproduction of the problem, but I found two mistakes in your code.

The first one is that you use dot "." inside contains(".title") and it's not needed.

The second one is that you are trying to add some styles not to DOM element, but Boolean, that is returned after contains(".title") part of your code.

My solution is here

if(title.value.classList.contains("title")) title.value.style.backgroundColor = 'red';
  • Related