The updates made to data in Vue.js are not reflecting on the screen

<template>
    <div class="parent">
        <div class="container">
            <h1 class="start" @click="start_timer">
                {{ timerText }}
            </h1>
        </div>
    </div>
</template>

<script>
    import Timer from 'easytimer.js';
    export default {
        name: 'GameStart',
        components: {

        },

        data() {
            return {
                timerText: "Start"
            }
        },

        methods: {
            start_timer() {

                var timer = new Timer();
                timer.start({countdown: true, startValues: {seconds: 4}});

                timer.addEventListener('secondsUpdated', function () {
                    this.timerText = timer.getTimeValues()['seconds'].toString();
                    console.log(this.timerText);

                })

                timer.addEventListener('targetAchieved', function () {
                    console.log('complete');
                    this.timerText = "COMPLETE!!";

                });

            }
        },

        mounted() {
            // var timer = new Timer();
            // timer.start();

            // timer.addEventListener('secondsUpdated', function () {
            //     console.log(timer.getTimeValues().toString());
            // });


        }
    }
</script>

<style>


    .parent {
        position: absolute;
        width: 100%;
        height: 100%;

        display: flex;
        justify-content: center;
        align-items: center;
    }

    .container {
        display: flex;
        justify-content: center;
        align-items: center;


    }

    .start {
        color: crimson;
        font-size: 50px;

    }

</style>

This code snippet represents a component in my vue.js project specifically designed for a mobile game. Upon clicking the 'start' h1 tag, the start_timer function is executed. Although I attempt to update the timerText variable in the start_timer function with countdown values (3, 2, 1), the changes are not reflected in the window display.

How can I modify the logic to implement a visible three-second countdown on the screen?

Answer №1

An issue commonly encountered with the keyword this

Within Vue, we often depend on this as a keyword that shares properties across the instance. However, a problem arises when we define a function using the keyword function.

Within that function, the term this now points to the function itself, rather than the overarching Vue component's this.

To circumvent this issue, avoid creating functions with the function keyword and instead utilize the fat-arrow notation, which preserves the original context of this.

Solution

Modify

timer.addEventListener('secondsUpdated', function () {
                    this.timerText = timer.getTimeValues()['seconds'].toString();
                    console.log(this.timerText);

                })

to

timer.addEventListener('secondsUpdated',  ()=> {
                    this.timerText = timer.getTimeValues()['seconds'].toString();
                    console.log(this.timerText);

                })

Answer №2

Your issue revolves around how to properly access the this keyword within a callback function.

When attempting to retrieve the component's data objects, it is recommended to utilize arrow functions because they do not have their own this binding (they retain the this value of the surrounding lexical context).

Therefore, it is advisable to convert your callback functions from regular functions to arrow functions.

timer.addEventListener('secondsUpdated', () => {
  // Here you can access your data objects/properties using the `this` keyword.
})

timer.addEventListener('targetAchieved', () => {
  // Here you can access your data objects/properties using the `this` keyword.
});

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

What is the best way to relocate an image or link using CSS?

I've been attempting to adjust the position of this image using CSS, but no matter how many times I try, it just refuses to budge. Can someone please help me troubleshoot what might be causing this issue? #yahoo1 { position: absolute; top: 100p ...

Once you address a block using jQuery

$(function(){ $(window).scroll(function () { var scrollVal = $(this).scrollTop(); var adscrtop =$(".header").offset().top // 在 RWD 767以下不作動 if(window.screen.width>767){ if(sc ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

Every page on Nextjs displaying identical content across all routes

I recently deployed a Next.js app using docker on AWS infrastructure. While the index page (/) loads correctly, I've noticed that the content of the index is also being loaded for every other route, including api routes, as well as the JavaScript and ...

Strategies for extracting taginput information from an API

I have a collection of tags stored in a database that I can retrieve using an API. Although I am able to use these tags within my template, I am facing issues specifically when trying to display them in the tag list. As someone who is new to Vue.js, I sus ...

Is it possible to trigger a mouseover event on a background div that is obscured by a foreground tooltip in jQuery?

I created a unique effect where a background div fades in when moused over, followed by the foreground div fading in. However, I encountered an issue where the tooltip ends up "flashing" as the foreground steals focus from the background. For reference, h ...

Setting up lint-staged for Vue projects: A step-by-step guide

After setting up a new Vue3 app using the Vue CLI and configuring Prettier as my linter, I decided to implement commitlint, husky, and lint-staged for validating commit messages and linting the code before pushing it. My Approach Following the instructio ...

Creating custom password confirmation validation in Vue.js using VeeValidate

In my current project, I have successfully implemented vee-validate with custom components. However, I am encountering difficulties when trying to set up a Password Confirmation input field. Within my custom components, such as <base-input-field>, ...

Can users be prevented from bookmarking a particular web page?

I'm working on a Python (Django) webpage and I need to prevent users from being able to bookmark a certain page. Is there a way to do this? ...

The Art of Determining the Text's Baseline

My goal is to create a test that determines whether the text rendered inside an <input> has the same baseline as a label: To achieve this, I want to calculate the baseline of the rendered text in each element and compare their values. Is it possible ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...

Top strategies for avoiding element tampering

What is the best solution for handling element manipulation, such as on Chrome? I have a button that can be hidden or disabled. By using Chrome's elements, it is possible to change it from hidden/disabled to visible/enabled, triggering my click functi ...

Jquery is causing some issues with the code provided:

This is the code snippet from script.js: $(document).ready(function() { $('#mainobject').fadeOut('slow'); }); Here is a glimpse of index.html: <!DOCTYPE html> <html> <head> <title>Hitler Map&l ...

Why does the UseEffect hook in next.js result in 2 fetch requests instead of the expected 1?

I am encountering an issue where my code is triggering two requests to my API using the GET endpoint. Unfortunately, my understanding of useEffect() is not deep enough to pinpoint where the problem lies. I want to avoid putting unnecessary strain on the ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Using the JS confirm function to switch the Vuetify checkbox in a Vue 2 application

It's been a real struggle trying to figure out this issue. I have a v-dialog that contains a checkbox. When the checkbox is clicked, a confirm() method is triggered to open a dialog in the browser to confirm the selection. After confirming, the check ...

Issues with Nuxt 3 middleware causing layout to fail updating post-navigation when using distinct login layout

Encountering a challenge in Nuxt 3 where the layout fails to update properly after navigation in a middleware, particularly when utilizing different layouts for the login page versus other pages. Here's an outline of the configuration: A middleware i ...

What is the best way to dynamically insert columns into HTML code?

This is an example of my HTML code: <div class="row text-center"> <div class="col h4">We Collaborate With:</div> <div class="col">company1</div> <div class="col">company2</div> ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...