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 excluding a plugin on Vue CLI3 in the vue.config.js file

Currently, I am working on Vue cli3 and trying to exclude the moment.js plugin using webpack. Despite following the rule provided, I keep encountering an error in vue.confing.js even after multiple attempts to modify it. plugins: [ new webpack.IgnoreP ...

Experiencing a lack of information when trying to retrieve data through an http request in an express/react

Issue: My problem lies in attempting to retrieve data from http://localhost:3000/auth/sendUserData using the http protocol. Unfortunately, I am not receiving any data or response, as indicated by the absence of console logs. Tools at my disposal: The te ...

Issues with functionality of React/NextJS audio player buttons arise following implementation of a state

I am currently customizing an Audio Player component in a NextJs application using the ReactAudioPlayer package. However, the standard Import Next/Audio and using just <Audio> without props did not yield the expected results. The player functions as ...

What is the best way to retrieve an array of objects that have a property matching another array?

In my array, I have data structured like this: array = [ { name: "john", tag: ["tag1", "tag2"] }, { name: "doe", tag: ["tag2"] }, { name: "jane", tag: ["tag2", "tag3"] } ]; My goal is to create a new array of objects that only contain elements with ...

Rename multiple files in bulk

With 10000 files consisting of php, html, css, and png formats that are interconnected to operate the website's engine, I am looking for a way to perform bulk renaming in order to ensure proper functionality. Not only do I need to rename the actual fi ...

Enhancing ajax requests with headers in Ember.js

My goal is to configure request headers for my emberjs application. However, when setting it up in the initializer, the client_id appears as [object Object] instead of the actual value. This is the initializer that runs when the application starts. Apikey ...

Jquery Timer that can be toggled on and off with a single button

I'm really struggling to find a way to make this work smoothly without any bugs. The button in the code below is supposed to perform three actions: Initiate a countdown when clicked (working) Stop the countdown automatically and reset itself when it ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

Unusual body padding found in the mobile design

When visiting on a mobile device and inspecting the elements in Google Chrome, try disabling the style rule overflow-x: hidden from the body element and then resizing the window. You may notice a white vertical stripe (padding) appearing on the right side ...

What techniques can be used to optimize the SEO of HTML generated by JavaScript? How does React.js go about achieving this

Is my webpage optimized for SEO if it was created using appendChild and innerHTML with JavaScript? Can react.js improve the SEO of a webpage? ...

Upon reloading, Nextjs static build automatically redirects users to the homepage

After creating a static Next.js build using npm run export, I encountered an issue while deploying the build on S3 or any other web server such as Apache with .htaccess or Nginx. When accessing the routes by pasting them directly into the browser, they wou ...

Utilizing autosuggest in combination with jQuery ajax consistently generates suggestions with a delay of 1 keystroke

I'm currently working on creating an autosuggest feature for a search box, but I've run into a problem. The suggestions that are displayed don't seem to match the current keystroke input (they keep showing suggestions based on the previous k ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Pass the response from a JavaScript confirm dialog to a Ruby program

Apologies if this question seems naive, but I am curious if it is feasible to pass the response from a JavaScript confirm box or message box as a value to a Ruby program. If I were to click on the "yes" button in the confirm box, could this response be st ...

The button is converting my text to a string instead of the integer format that I require

Hello everyone, I've been grappling with this button conundrum for the last 45 minutes, and I can't seem to find a solution. I have created three different buttons in my code snippet below. (html) <div class="action"> ...

Basic game of tic tac toe using JavaScript and jQuery

Teaching myself the ropes of JavaScript/jQuery, I decided to dive into building a simple tic tac toe game. Following this example as a guide, I embarked on creating my own version. While most parts seem to be working smoothly, there's one problem that ...

Implement ajax functionality to update an object within a JSP page

On my JSP page, I have implemented an accordion list (utilizing Bootstrap 3) with text and a Delete button within each node. When the user clicks on the delete button, that specific list item is removed. To construct the accordion list, I bring in an Array ...

Creating JSON from identical user interface components

I have created a form similar to this one: https://jsfiddle.net/6vocc2yn/ that generates a JSON output like below: { "List": [ { "Id": 10, "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10", "email": "<a href="/cdn-cgi/l/email-pr ...

The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it doe ...

Transforming Json data into an Object using Angular 6

https://i.stack.imgur.com/JKUpL.png This is the current format of data I am receiving from the server, but I would like it to be in the form of an Object. public getOrder(): Observable < ORDERS > { return this._http.get < ORDERS > (`${thi ...