programing

Vue.js - 원본 양식 데이터가 변경되지 않는 한 제출 버튼 비활성화

bestcode 2022. 8. 30. 22:18
반응형

Vue.js - 원본 양식 데이터가 변경되지 않는 한 제출 버튼 비활성화

저는 실험용으로 만든 단순한 형태를 가지고 있습니다.원본 양식 데이터가 변경되지 않는 한 버튼을 비활성 상태로 유지하려고 하지만, 데이터 변경이 원래 데이터로 되돌아갔을 경우(실행 취소) 버튼은 비활성 상태로 유지하려고 합니다.

<template lang="pug">
  form(@click.prevent="save")
    .main
      input(v-model="user.name")
      input(v-model="user.email")
      input(v-model="user.age")
      select(v-model="user.sex")
        option Male
        option Female
    .footer
      button(:disabled="isFormEnable") Save
</template>

<script>
export default {
  name: 'userForm',
  data () {
    return {
      user: {
        name: 'John Doe',
        email: 'john@gmail.com',
        age: '35',
        sex: 'Male',
      }
    }
  },

  computed: {
    isFormEnable () {
      // I am not sure what I need to do here but something like this may be:
      if (user.name) { return true }
    }
  },

  methods: {
    save () {
      console.log('Form Submitted')
    }
  }
}
</script>

여기서 jQuery 솔루션을 찾았는데 vanilla/vue javascript 솔루션을 찾고 있습니다.

$('form')
    .each(function(){
        $(this).data('serialized', $(this).serialize())
    })
    .on('change input', function(){
        $(this)             
            .find('input:submit, button:submit')
                .prop('disabled', $(this).serialize() == $(this).data('serialized'))
        ;
     })
    .find('input:submit, button:submit')
        .prop('disabled', true)
;

1개의 모듈의 도움을 받아 다음과 같이 합니다.

npm i deep-diff

deep-diff오브젝트 값을 비교하기 위한 것입니다.

<script>
import { diff } from "deep-diff";

// default form value
const defaultUser = {
  name: "John Doe",
  email: "john@gmail.com",
  age: "35",
  sex: "Male"
};

export default {
  //...
  data() {
    return {
      user: { ...defaultUser } // cloning the object using object spread syntax
    };
  },

  computed: {
    isFormEnable() {
      // check if it's default value
      if (!diff(this.user, defaultUser)) return false;

      return true;
    }
  },
  //...
};
</script>

Calculated 속성 및 Watch 속성으로 기본적으로 수행하는 방법은 다음과 같습니다.

<template>
  <form>
    <label>Name</label>
    <input v-model='form.name' />

    <label>Age</label>
    <input v-model='form.age' />

    <button :disabled="!changed">Save</button>
  <form>
</template>
<script>
import _ from 'lodash'

export default {
  data() {
    return {
      changed: false, // for storing form change state
      form: {}, // data variable to store current form data binding
    }
  },

  computed: {
    // store the original form data
    originalForm() {
      return this.$store.state.form
    }
  },
  
  watch: {
    // by watching the original form data
    // create a clone of original form data
    // and assign it to the form data variable
    originalForm() {
      this.form = _.cloneDeep(this.originalForm)
    },

    // watch the changes on the form data variable
    form: {
      handler() {
        // using lodash to compare original form data and current form data
        this.changed = !_.isEqual(this.form, this.originalForm)
      },
      // useful to watch deeply nested properties on a data variable
      deep: true,
    },
  },

  created() {
    // dispatch an action to fill the store with data
    this.$store.dispatch('init')
  }
}
</script>

자세한 내용은 이 블로그를 참조하십시오.

언급URL : https://stackoverflow.com/questions/49623074/vue-js-disable-submit-button-unless-original-form-data-has-changed

반응형