Encountering an issue in a Vue console where the $ref is returning null and prompting an error message

It's puzzling why I keep encountering a console error in Vue that says "cannot read null of a $ref". Despite having the correct HTML template and adding logic to the script tag as needed, I'm still facing this issue - Cannot read properties of null (reading 'style'). I've defined the template $refs following the guidelines in the Vue documentation, but it seems like Vue is not accepting it. https://codesandbox.io/s/silly-wave-de7yk5?file=/src/components/HelloWorld.vue:0-2494

<template>
  <div class="clock">
    <div class="clock-face">
      <div class="hand secHand" ref="secHand"></div>
      <div class="hand minHand" ref="minHand"></div>
      <div class="hand hourHand" ref="hourHand"></div>
      <div class="circle"></div>
    </div>
    <select
      name="box-1"
      id="select"
      @Change="selectedHour"
      v-model="selectedHour"
    >
      <option class="option" value="0">0 UTC</option>
      <option class="option" value="1">+1 UTC</option>
      <option class="option" value="2">+2 UTC</option>
      <option class="option" value="3">+3 UTC</option>
      <option class="option" value="4">+4 UTC</option>
      <option class="option" value="5">+5 UTC</option>
      <option class="option" value="6">+6 UTC</option>
      <option class="option" value="7">+7 UTC</option>
      <option class="option" value="8">+8 UTC</option>
      <option class="option" value="9">+9 UTC</option>
      <option class="option" value="10">+10 UTC</option>
      <option class="option" value="11">+11 UTC</option>
    </select>
  </div>
</template>

<script>
const secondHand = document.querySelector(".secHand");
const minuteHand = document.querySelector(".minHand");
const hourHand = document.querySelector(".hourHand");

// const select = document.querySelector("#select");
// let selectValue = select.value;

let secHand = this.$refs.secHand;
function setDate() {
  const now = new Date();

  const seconds = now.getSeconds();
  const secondsDegrees = (seconds / 60) * 360 + 90;
  this.secHand.style.transform = `rotate(${secondsDegrees}deg)`; // getting the error at this line
  if (secondsDegrees === 90) {
    secHand.style.transition = "none";
  } else if (secondsDegrees >= 91) {
    secHand.style.transition = "all 0.05s cubic-bezier(0.1, 2.7, 0.58, 1)";
  }

  const minutes = now.getMinutes();
  const minutesDegrees = (minutes / 60) * 360 + 90;
  minuteHand.style.transform = `rotate(${minutesDegrees}deg)`;

  const hours = now.getHours();

  let newHour = hours + selectValue;

  const hoursDegrees = (newHour / 12) * 360 + 90;
  hourHand.style.transform = `rotate(${hoursDegrees}deg)`;
}

setInterval(setDate, 1000);

export default {
  name: "HelloWorld",
  data() {
    return {
      selectedHour: "",
    };
  },
  props: {},
};
</script>

Answer №1

If you find yourself attempting to access this.$refs in your code outside of the Vue.js framework, you may run into issues.

let secHand = this.$refs.secHand;

To properly access $refs, make sure you are doing so within a Vue.js App context rather than outside of it!

Move your setDate() function as a method inside Vue and it should function correctly.

data() {
    return {
      selectedHour: "",
    };
  },
methods: {
   setDate() {
     let secHand = this.$refs.secHand;
   }
}

For handling dynamic css styles, consider utilizing Vue's SFC CSS Features

Refer to Template Refs for more information.

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

Tips for previewing files before uploading them to a server utilizing the file-upload feature of vue.js and element-ui

I am currently utilizing vue.js and element-ui for file uploads and previews. My goal is to be able to preview files (.pdf/.docx/.jpg, etc.) before they are uploaded to the server. <el-upload ref="uploadFile" :on-change="onUploadCh ...

Using the React key attribute for components without distinct identifiers

When dealing with a situation where users need to provide a list of timeframes, it can be tricky to generate a unique key for each component in React. Simply using the index of the array is not sufficient, as items can be removed from the middle of the lis ...

How to bind parent object scope to MySQL query's anonymous callback in Node.js

As a newcomer to node.js, I am still working on understanding the concept of scoping anonymous functions. I have created an object with multiple methods and within one of my methods, I retrieve a MySQL connection from a pool and then execute a query on tha ...

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...

Ways to ensure that the height of the second row in the second column matches that of the first column

My current layout design is causing an issue where the lower green box extends beyond the total height of the entire box. I've provided a rough version of my code on codepen. Using the Bulma framework, my goal is to align the height of the left column ...

Member not found error with JQuery Autocomplete on browsers older than Internet Explorer 10

While constructing a web page with JQuery, I encountered issues with my autocomplete feature when testing it on IE8. The error message reads: SCRIPT3: Member not found. jquery-1.6.4.min.js, line 2 character 29472 After extensive research, I have been u ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Automatically adjusting the placement of the hashtag within the URL when a button link is clicked in a Vue application

I am currently troubleshooting an issue with vue router within a custom library I am working on. The majority of the code was already developed before my involvement, and I have encountered a problem with implementing a back button on a specific page relat ...

Click event to reset the variable

The code snippet in Javascript below is designed to execute the function doSomethingWithSelectedText, which verifies if any text is currently selected by utilizing the function getSelectedObj. The getSelectedObj function returns an object that contains in ...

Update the Vue component upon fetching new data

How can I continuously refresh the list of items when a button in a sibling component is clicked? The watch method only triggers once, but I need it to constantly refresh. This is the parent element: <template> <div class="container"& ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

Tips for displaying response data from Vue Apollo using the <script setup> syntax

I recently followed a tutorial on Vue Apollo for fetching data using a fake API at https://www.apollographql.com/blog/frontend/getting-started-with-vue-apollo/. However, I've written some code that utilizes the <script setup></script> ins ...

Retrieving objects from Firebase in a loop using promises

Seeking guidance on handling promises in AngularJS as a newcomer. Struggling with merging data from two asynchronous arrays into a single array within a for-loop. Encountering a bug where the same picture is displayed for all entries despite different user ...

Caution: Make sure to assign an object to a variable before exporting it as the default module

While working with react-redux, my root Reducer appears like this: import Customers from "./customers/reducer"; export default { Customers }; Recently, I encountered a warning saying: Assign object to a variable before exporting as module def ...

Is it possible for me to manually access the vue-router parser?

Is there a way to access the vue-router parser in order to evaluate a link before navigating to it? In other words: Suppose I have the path /one/two/three but it is not currently the active path. I would like to check if that path matches any defined rout ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...

Retrieval of each single row from a PHP-generated JSON dataset

This is quite challenging, especially for me. My goal here is to use Javascript to extract each value of every row in this JSON data: {"id":2,"url":"image.png","x":19,"y":10,"user_id":20} {"id":3,"url":"image.png","x":19,"y":10,"user_id":20} {"id":4,"url" ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...

How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item. Can anyone provide some guidance? Thank you! This is the JavaScript used: <script> show() $(functi ...