[Vuejs]-How can I write this code to be more efficient

1👍

You can put the exercise data into its own object, and save that to localStorage instead. E.g.:

<script>
const app = new Vue({
  el:'#app',
  data: {
    exercises: {},
  },
  mounted() {
    this.exercises = JSON.parse(localStorage.getItem("exercises"));
  },
  watch: {
    exercises(newExerciseValues) {
      localStorage.setItem("exercises", JSON.stringify(newExerciseValues));
    },
  }
})
</script>

If you really need to store and retrieve the individual exercises explicitly, I would recommend keeping the data in one exercises object, and simply use a for loop to check/set everything. Something like this:

[...]
watch: {
  exercises(newExercises) {
    const exercisesToCheck = [
      'explosive_pullups_1',
      'explosive_pullups_2',
      'explosive_pullups_3',
      'tuck_front_raises_1',
      'tuck_front_raises_2',
      'tuck_front_raises_3',
    ];

    for (const exercise of exercisesToCheck) {
      localStorage.setItem(exercise, this.exercises[exercise]);
    }
  },
},
[...]

On a side note, be very careful when working with objects in Vue. If you need to add a new exercise to the exercises object, avoid using this.exercises['new_exercise'] = newExercise. Instead, use Vue.set(this.exercises, 'new_exercise', newExercise). Check out the Vue docs for an explanation.

Leave a comment