动态类绑定svg和vue不起作用

问题描述 投票:0回答:2

我尝试为我的一个学生制作打字程序。我使用SVG生成单词,并使用类绑定与vuejs。当用户按下右键时,字符的颜色应该改变。但由于某种原因它不起作用。谁能告诉我哪里出错了?

当我为数组分配更改时,单击按钮,它可以正常工作。当我在按下按键后控制数组时,数组会被更改,但字符的颜色不是!

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>
javascript vue.js svg
2个回答
0
投票

看。我只是改变了一切。

将其添加到您的方法中。并从计算中删除它。

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

然后我将checkLetter更改为此

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++
            }
        }

0
投票

我找到了解决方案。但我不明白为什么它有效。我刚刚为我的数据添加了一个名为'test'的变量。在checkletter方法中,我添加了一行来将测试var分配给字符串化数组,就像这样

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++


            }
        }

在html模板中,我还添加了一个隐藏的div,我输出测试值。

© www.soinside.com 2019 - 2024. All rights reserved.