如何编写此代码以提高效率

时间:2019-09-29 16:20:28

标签: vue.js local-storage code-cleanup

我正在学习Vue.js,并且正在建立一个使用LocalStorage存储数据的网站。

我写了一些代码,这有点笨拙而且很重复:

<script>
const app = new Vue({
  el:'#app',
  data:{
    explosive_pullups_1: '',
    explosive_pullups_2: '',
    explosive_pullups_3: '',
    tuck_front_raises_1: '',
    tuck_front_raises_2: '',
    tuck_front_raises_3: '',
  },
  mounted() {
    if (localStorage.explosive_pullups_1) {
      this.explosive_pullups_1 = localStorage.explosive_pullups_1;
    }
    if (localStorage.explosive_pullups_2) {
      this.explosive_pullups_2 = localStorage.explosive_pullups_2;
    }
    if (localStorage.explosive_pullups_3) {
      this.explosive_pullups_3 = localStorage.explosive_pullups_3;
    }
    if (localStorage.tuck_front_raises_1) {
      this.tuck_front_raises_1 = localStorage.tuck_front_raises_1;
    }
    if (localStorage.tuck_front_raises_2) {
      this.tuck_front_raises_2 = localStorage.tuck_front_raises_2;
    }
    if (localStorage.tuck_front_raises_3) {
      this.tuck_front_raises_3 = localStorage.tuck_front_raises_3;
    }
  },
  watch: {
    explosive_pullups_1(pullups1) {
      localStorage.explosive_pullups_1 = pullups1;
    },
    explosive_pullups_2(pullups2) {
      localStorage.explosive_pullups_2 = pullups2;
    },
    explosive_pullups_3(pullups3) {
      localStorage.explosive_pullups_3 = pullups3;
    },
    tuck_front_raises_1(tuck_front_raises1) {
      localStorage.tuck_front_raises_1 = tuck_front_raises1;
    },
    tuck_front_raises_2(tuck_front_raises2) {
      localStorage.tuck_front_raises_2 = tuck_front_raises2;
    },
    tuck_front_raises_3(tuck_front_raises3) {
      localStorage.tuck_front_raises_3 = tuck_front_raises3;
    },
  }
})
</script>

我想知道一种减少重复性的代码。

1 个答案:

答案 0 :(得分:1)

您可以将练习数据放入其自己的对象中,然后将其保存到localStorage中。例如:

<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>

如果确实需要显式存储和检索单个练习,我建议将数据保留在一个exercises对象中,并简单地使用for循环来检查/设置所有内容。像这样:

[...]
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]);
    }
  },
},
[...]

另一方面,在Vue中使用对象时要非常小心。如果您需要向exercises对象添加新的练习,请避免使用this.exercises['new_exercise'] = newExercise。而是使用Vue.set(this.exercises, 'new_exercise', newExercise)。查看Vue docs以获得解释。