浏览代码

fix: auto save only if there is no save button (#1116)

* refactor: make code more declarative

* fix: auto save only if there is no save button
Gerald 4 年之前
父节点
当前提交
09a82e95bf
共有 1 个文件被更改,包括 30 次插入27 次删除
  1. 30 27
      src/common/ui/setting-text.vue

+ 30 - 27
src/common/ui/setting-text.vue

@@ -2,11 +2,11 @@
   <div>
     <textarea
       class="monospace-font"
-      :class="{'has-error': error}"
+      :class="{'has-error': parsedData.error}"
       spellcheck="false"
       v-model="value"
       :disabled="disabled"
-      :title="error"
+      :title="parsedData.error"
       @change="onChange"
     />
     <button v-if="hasSave" v-text="i18n('buttonSave')" @click="onSave"
@@ -37,49 +37,52 @@ export default {
   data() {
     return {
       value: null,
-      jsonValue: null,
-      error: null,
-      canSave: null,
-      canReset: null,
+      savedValue: null,
     };
   },
+  computed: {
+    parsedData() {
+      let value;
+      let error;
+      if (this.json) {
+        try {
+          value = JSON.parse(this.value);
+        } catch (e) {
+          error = e.message || e;
+        }
+      } else {
+        value = this.value;
+      }
+      return { value, error };
+    },
+    canSave() {
+      return !this.parsedData.error && !deepEqual(this.parsedData.value, this.savedValue || '');
+    },
+    canReset() {
+      return !deepEqual(this.parsedData.value, this.defaultValue || '');
+    },
+  },
   created() {
     const handle = this.json
       ? (value => JSON.stringify(value, null, '  '))
       // XXX compatible with old data format
       : (value => (Array.isArray(value) ? value.join('\n') : value || ''));
     this.revoke = hookSetting(this.name, val => {
-      this.savedValue = val;
-      val = handle(val);
-      if (this.value !== val) this.value = val; // will call onInput
-      else this.onInput(val);
+      this.savedValue = Object.seal(val);
+      this.value = handle(val);
     });
     this.defaultValue = objectGet(defaults, this.name);
-    this.$watch('value', this.onInput);
   },
   beforeDestroy() {
     this.revoke();
   },
   methods: {
-    onInput(val) {
-      if (this.json) {
-        try {
-          val = JSON.parse(val);
-          this.jsonValue = val;
-          this.error = null;
-        } catch (e) {
-          this.error = e.message || e;
-        }
-      }
-      this.canSave = this.hasSave && !this.error && !deepEqual(val, this.savedValue || '');
-      this.canReset = this.hasReset && !deepEqual(val, this.defaultValue || '');
-    },
     onChange() {
-      if (!this.error) {
-        options.set(this.name, this.json ? this.jsonValue : this.value);
-      }
+      // Auto save if there is no `Save` button
+      if (!this.hasSave && this.canSave) this.onSave();
     },
     onSave() {
+      options.set(this.name, this.parsedData.value);
       this.$emit('save');
     },
     onReset() {