我在 Vue 中作業,我正在使用setInterval()和data()屬性動態更改文本。
我有一個作業方法,但我想知道是否有更有效/優化該方法的方法......或者它是否盡可能優化?
優化含義:最適合記憶體使用以及代碼是否盡可能簡單?
<h1>
<span>{{ action }}</span> for everyone.
</h1>
<script>
export default {
name: "HeadLine",
data() {
return {
action: "Build",
};
},
methods: {
changeTitle() {
setInterval(() => {
const actions = ["Build", "Create", "Design", "Code"];
const currentActionIndex = actions.indexOf(this.action);
//Send back to index of [0] === Build
const nextActionIndex = (currentActionIndex 1) % 4;
let nextAction = actions[nextActionIndex];
this.action = nextAction;
}, 3000);
},
},
};
</script>
uj5u.com熱心網友回復:
渲染方面,Vue 已經做得最好了。
關于你的文本旋轉功能,可以稍微改進一下,但它是一個簡單的功能,你不會獲得太多的記憶體使用。
// Stores the actions out of the component. It doesn't need to be reactive if it's static.
// You're avoiding having Vue's proxy above this array.
const actions = ["Build", "Create", "Design", "Code"];
export default {
data () {
return {
// The only reactive data you need is the index of the word you want to show
wordIndex: 0,
}
},
computed: {
// Let view update the text when the index changes. Computed properties use caching.
action() {
return actions[this.wordIndex]
}
},
methods: {
changeTitle() {
setInterval(this.initRotation, 3000)
},
initRotation () {
// Update the current word index
this.wordIndex = (this.wordIndex 1) % actions.length;
}
},
beforeDestroy() {
// Remove the interval runner when the component is destroyed!
clearInterval(this.initRotation)
}
}
如前所述,這不會徹底改變組件的性能。感覺變化已經太簡單了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481873.html
標籤:javascript Vue.js
上一篇:在可組合物vue3中使用道具
