The issue with the text not updating after upgrading to Vue 3 has not been

I am currently in the process of reworking a component for Vue 3, specifically using their new setup script to improve the code readability. This is what the current code looks like:

export default {
    name: "typeWriter",
    data: () => {
        return {
            typeValue: "",
            typeStatus: false,
            displayTextArray: ['Art', 'Science', 'Math', 'Everything'],
            typingSpeed: 70,
            erasingSpeed: 70,
            newTextDelay: 1000,
            displayTextArrayIndex: 0,
            charIndex: 0,
        };
    },
    created() {
        setTimeout(this.typeText, this.newTextDelay + 200);
    },
    methods: {
        typeText() {
            if (this.charIndex < this.displayTextArray[this.displayTextArrayIndex].length) {
                if (!this.typeStatus) {
                    this.typeStatus = true;
                }

                this.typeValue += this.displayTextArray[this.displayTextArrayIndex].charAt(this.charIndex);
                this.charIndex++;

                setTimeout(this.typeText, this.typingSpeed);
            } else {
                this.typeStatus = false;

                if (this.displayTextArrayIndex + 1 >= this.displayTextArray.length) {
                    return
                }

                setTimeout(this.eraseText, this.newTextDelay);
            }
        },
        eraseText() {
            if (this.charIndex > 0) {
                if (!this.typeStatus) {
                    this.typeStatus = true;
                }

                this.typeValue = this.displayTextArray[this.displayTextArrayIndex].substring(0, this.charIndex - 1);
                this.charIndex -= 1;

                setTimeout(this.eraseText, this.erasingSpeed);
            } else {
                this.typeStatus = false;
                this.displayTextArrayIndex++;

                setTimeout(this.typeText, this.typingSpeed + 1000);
            }
        },
    },
};

Below is the new Vue 3 code using

<script setup lang="ts">

let typeValue = ""
let typeStatus = false
let displayTextArray = ['Art', 'Science', 'Math', 'Everything']
let typingSpeed = 70
let erasingSpeed = 70
let newTextDelay = 1000
let displayTextArrayIndex = 0
let charIndex = 0

setTimeout(typeText, newTextDelay);

function typeText() {
    if (charIndex < displayTextArray[displayTextArrayIndex].length) {
        if (!typeStatus) {
            typeStatus = true;
        }

        typeValue += displayTextArray[displayTextArrayIndex].charAt(charIndex);
        charIndex++;

        setTimeout(typeText, typingSpeed);
    } else {
        typeStatus = false;

        if (displayTextArrayIndex + 1 >= displayTextArray.length) {
            return
        }

        setTimeout(eraseText, newTextDelay);
    }
}

function eraseText() {
    if (charIndex > 0) {
        if (!typeStatus) {
            typeStatus = true;
        }

        typeValue = displayTextArray[displayTextArrayIndex].substring(0, charIndex - 1);
        charIndex -= 1;

        setTimeout(eraseText, erasingSpeed);
    } else {
        typeStatus = false;
        displayTextArrayIndex++;

        setTimeout(typeText, typingSpeed + 1000);
    }
}

The issue I am facing is that the Vue 2 code correctly updates a div with the value in typeValue, whereas the new Vue 3 code is not updating the div. I have added a console.log statement and confirmed that the code is working, but the div is not reflecting the change in typeValue. I am at a loss as to why this is happening and would appreciate any guidance on resolving this in Vue 3.

As I am still new to Vue 3, it is possible that I missed something, but based on my current understanding, everything seems correct, making it difficult for me to determine why the div is not updating as expected.

Answer №1

Ensure your data is interactive by using ref:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    let typeValue = ref("")
    let typeStatus = false
    let displayTextArray = ['History', 'Technology', 'Language', 'Innovation']
    let typingSpeed = 80
    let erasingSpeed = 80
    let newTextDelay = 1200
    let displayTextArrayIndex = ref(0)
    let charIndex = 0
    
    setTimeout(enterText, newTextDelay);
    
    function enterText() {
      if (charIndex < displayTextArray[displayTextArrayIndex.value].length) {
        if (!typeStatus) {
          typeStatus = true;
        }
        typeValue.value += displayTextArray[displayTextArrayIndex.value].charAt(charIndex);
        charIndex++;
        setTimeout(enterText, typingSpeed);
      } else {
        typeStatus = false;
        if (displayTextArrayIndex.value + 1 >= displayTextArray.length) {
          return
        }
        setTimeout(deleteText, newTextDelay);
      }
    }

    function deleteText() {
      if (charIndex > 0) {
        if (!typeStatus) {
          typeStatus = true;
        }
        typeValue.value = displayTextArray[displayTextArrayIndex.value].substring(0, charIndex - 1);
        charIndex -= 1;
        setTimeout(deleteText, erasingSpeed);
      } else {
        typeStatus = false;
        displayTextArrayIndex.value++;
        setTimeout(enterText, typingSpeed + 1000);
      }
    }
    return {
      typeValue, deleteText, enterText
    };
  },
})
app.mount('#sample')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="sample">
  <input type="text" :value="typeValue" />
</div>

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

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

Differences between Typescript static methods and functions defined outside of classesWhen comparing Types

What distinguishes a static class method from a function defined outside a class in TypeScript, especially when visibility is not a concern? While there are differences in visibility from other classes and files, what factors should be considered when dec ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

Refreshing Custom Functions within Excel Add-On - Web Edition

Currently, I am working on an Excel Add-In that includes custom functions utilizing the Javascript API. I have been following a particular tutorial for guidance. While attempting to debug using the Web version of Excel due to its superior logging capabili ...

Why Mixin Class inference is not supported in Typescript

I encountered an issue in my code: The error message 'Property 'debug' does not exist on type 'HardToDebugUser'.' was displayed. It seems like Typescript failed to infer the mixin class correctly. Can you please explain this t ...

Displaying an error message following the dynamic retrieval of the input field's value

How can I display an error message when a specific field with a value of 0 is not filled out in my Angular reactive forms? In my form, I have added a dropdown which is mandatory and I have implemented validators to ensure it is required. The validator work ...

Currently, I am utilizing Vue and its routing capabilities to create a hybrid application. I am seeking a way to store certain data in the history state so that I can easily restore it when navigating back to previous pages. Any

One interesting aspect of Android apps is that when a new activity is started, the original activity remains intact with all its internal data. This ensures that when you return to the original activity, everything is as you left it. How can I achieve sim ...

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

refresh the React component without having to refresh the entire webpage

Hey there, I have a component with a function called "handleAvatarUpload". Currently, when there is a change, the entire page reloads instead of just the component. Is there a way to reload only the component without refreshing the whole page? import { us ...

Investigating SCSS Issues: The Problem with Absolute Imports

I am working on a project with the following structure: - my/project - assets - images - image-name.svg - source - components - MyComponent - MyComponent.module.scss - ... - ... ...

Tips for uploading images using Rails-Api, Vue.js, Cloudinary, and Attachinary

In my experience working with server-rendered Rails applications, I have relied on Cloudinary and Attachinary for uploading images and files to an external server and linking them to my data models. As I transition to using Vue.js with Rails-API more freq ...

Mouse event listener includes timeout function that updates a global variable

I'm currently working on a function that gets activated by a mouse click, but there's a 10-second cooldown period using setTimeout() before it can be triggered again. However, after the timeout, my variable doesn't get set to the correct boo ...

Creating a Lambda function in CDK: A guide to configuring the Dockerfile and setting environment variables

I am currently working on a SAM project using template.yml. Here is a snippet of the configuration: Globals: Function: Timeout: 30 Environment: Variables: DBNAME: !Ref DBNAME Resources: MessageFunction: Type: AWS::Serverless: ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

Getting started with integrating Vue.js with Lumen: a step-by-step guide

After successfully creating a RESTful API using Lumen and testing it with Postman, I am now looking to develop the front end for it with Vue. What is the best approach for integrating Vue into my existing project? Should I create a separate directory for ...