I am working in Vue and I am dynamically changing text using setInterval()
and a data()
property.
I have a working method but I am wondering if there is a more efficient/way to optimize the method...or is it as optimized as it can be?
Optimize meaning: best for memory usage as well as is the code as simple as it can be?
<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>
CodePudding user response:
Rendering speaking, Vue is already doing the best job possible.
About your text rotating function, it can be improved a little bit, but it's a simple function, you won't gain much of memory usage.
// 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)
}
}
As said, this won't change drastically the component performance. It's already too simple to feel a change.