我正在尝试为 vue 3 重写一个组件,更具体地说,使用他们的新设置脚本,以便代码看起来更简洁,这是当前的样子。
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;
// stop the typing once we hit the last thing we wish to type.
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);
}
},
},
};
这是使用
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;
// stop the typing once we hit the last thing we wish to type.
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);
}
}
我遇到的问题是,vue 2 代码会使用 typeValue 中的值正确更新 div,新的 vue 3 代码不会更新div,我添加了一个 console.log,可以看到代码确实正在触发并工作,div 只是没有识别 typeValue 中的这种变化,我完全不明白为什么会这样。
我还是 vue 3 的新手,所以也许我错过了一些东西,但这对我来说看起来很正确,所以我不明白为什么 div 没有像以前那样更新。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号