Issue with binding classes dynamically in vue with svg elements

I'm attempting to create a custom typing program for one of my students using SVG to display the words and class binding with Vue.js. The goal is to change the color of the characters when the correct key is pressed by the user. However, I've encountered an issue as it's not working as expected. Can anyone help me identify where I made a mistake?

Interestingly, when I manually make changes to the array with a button click, it functions properly. Additionally, when I log the array after a key press event, the array is updated; yet, the character color remains unchanged!

export default {

    data(){
        return{
            word:["a","p","p","e","l","m","o","e","s"],
            letterId:0,
            kleur:[false,false,false,false,false,false,false,false,false],
         }
    },
    methods:{
        checkLetter(event){
            console.log('key pressed: ' + event.which)
            console.log('letter' +this.letterId+' is: ' + this.letter)
            
            if(event.key == this.letter){
                console.log("correct key was pressed")
                this.kleur[this.letterId] = true
                this.letterId++
            }
        }
    },
    computed:{
        
        letter(){
            //determine which letter is expected
            return this.word[this.letterId]
        },
        viewbox(){
            //adjust viewbox according to the length of the word
            var width = (this.word.length * 50) + 50
            return "0 0 "+width + " 70"
        }

    },
    created: function () {
            window.addEventListener('keyup', this.checkLetter)
    },


}
.green{
    font: bold 35px Courier;
    fill:green;
}
.normaal{
   font: bold 35px Courier;
    fill:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div> 
    <svg :viewBox="viewbox" width="100%">
        <text v-for="letter,index in word" :x="index*40" y="45"  :id="index" :class="{green:kleur[index], normaal:!kleur[index]}">{{letter}}</text>
     </svg>   
    </div>
</template>

Answer №1

Wow, everything has been completely transformed.

Please incorporate this into your methods and remove it from the computed section.

//locate the letter within the array and return it 
letter(letter){
              return this.word.find(element => {
                  return element == letter;
              })
        },

Next, I updated checkLetter as follows:

checkLetter(event){
            console.log('eventkey: ' + this.letter(event.key));
            //if it finds it then the correct key wes pressed. 
            if(event.key == this.letter(event.key)){
                console.log("correct key was pressed")
                this.kleur[this.letterId] = true
                this.letterId++
            }
        }

Answer №2

I have successfully discovered a resolution, however the reason behind its functionality eludes me. I simply introduced a variable named 'test' to my dataset. Additionally, within the checkletter method, I included a line that assigns the test variable to the stringified array as shown below:

checkLetter(event){
            console.log('key pressed: ' + event.which)
            console.log('letter' +this.letterId+' is: ' + this.letter)

            if(event.key == this.letter){
                console.log("correct key was pressed")
                this.kleur[this.letterId] = true
                //modification
                this.test = this.kleur.toString()
                this.letterId++

            }
        }

In the HTML template, I have also implemented a concealed div where the value of test is displayed.

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 are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Updating Vuetify MDI icons in Nuxt.js: A Step-by-Step Guide

When using Vuetify with Nuxt.js, I am facing an issue where some material design icons are not displaying properly. For example, <v-icon>mdi-cog</v-icon> appears as blank. However, other icons are working fine. nuxt.config.js buildModules: ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

HTML integration of JavaScript not working as expected

My experience with separating files in HTML and JS has been positive - everything works smoothly when I link the JS file to the HTML. However, an issue arises when I decide to include the JS code directly within <script> tags in the HTML itself. The ...

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

Installing the error package resulted in the following error: "Error: module 'nopt' not found."

After attempting to install node modules, I encountered the error message "Error: cannot find module 'nopt'." I tested various solutions, but none of them seemed to work. The image below shows the attached error message. { "name": "server", ...

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

Oops! There seems to be a mistake - the provider setPageProvider is not recognized

Struggling to implement pagination on my page using the AngularJS framework. Encountering the error Error: [$injector:unpr] Unknown provider: setPageProvider <- setPage. Despite rearranging the code, the issue persists. Attempted following a tutorial fr ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

Display array elements without numerical indexes

Consider the code snippet below: for(i=0; i<3; i++){ a = {}; a['name' + i] = i; data.push(a); } This code will generate the following array: { 1:{name0:0}, 2:{name1:1}, 3:{name2:2} } How can I modify the code ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

Refreshing JWT tokens using Vue resource interceptor

I am currently working on creating a custom vue-resource interceptor that handles the refreshing of JWT access tokens upon expiration. My approach involves implementing a post-request callback to detect token expiration errors (status == 401). The idea is ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Exploring AngularJS: Effiecient Looping and Styling

Being a beginner in AngularJS, please excuse me if this question seems silly. I want to display my data in a grid format (using Ionic) where each row has separate columns like this: <div class="row"> <div class="col-33">Item 1</div> ...