我正在嘗試為 vue 3 重寫一個組件,更具體地說,使用他們的新設(shè)置腳本,以便代碼看起來更簡潔,這是當(dāng)前的樣子。
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); } }, }, };
這是使用 嘗試使用
ref
使數(shù)據(jù)具有反應(yīng)性一個>:const { ref } = Vue
const app = Vue.createApp({
setup() {
let typeValue = ref("")
let typeStatus = false
let displayTextArray = ['Art', 'Science', 'Math', 'Everything']
let typingSpeed = 70
let erasingSpeed = 70
let newTextDelay = 1000
let displayTextArrayIndex = ref(0)
let charIndex = 0
setTimeout(typeText, newTextDelay);
function typeText() {
if (charIndex < displayTextArray[displayTextArrayIndex.value].length) {
if (!typeStatus) {
typeStatus = true;
}
typeValue.value += displayTextArray[displayTextArrayIndex.value].charAt(charIndex);
charIndex++;
setTimeout(typeText, typingSpeed);
} else {
typeStatus = false;
if (displayTextArrayIndex.value + 1 >= displayTextArray.length) {
return
}
setTimeout(eraseText, newTextDelay);
}
}
function eraseText() {
if (charIndex > 0) {
if (!typeStatus) {
typeStatus = true;
}
typeValue.value = displayTextArray[displayTextArrayIndex.value].substring(0, charIndex - 1);
charIndex -= 1;
setTimeout(eraseText, erasingSpeed);
} else {
typeStatus = false;
displayTextArrayIndex.value++;
setTimeout(typeText, typingSpeed + 1000);
}
}
return {
typeValue, eraseText, typeText
};
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<input type="text" :value="typeValue" />
</div>