Skip to content

Instantly share code, notes, and snippets.

@mul14
Last active January 15, 2019 10:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mul14/d3d9aa95311b6a7fff5d3b69c5ccf6da to your computer and use it in GitHub Desktop.
Save mul14/d3d9aa95311b6a7fff5d3b69c5ccf6da to your computer and use it in GitHub Desktop.
Vue.js Form class

Usage

<input type="text" v-model="email">

<input type="text" v-model="username">

<button type="button" @click="save">Save</button>

<button type="button" @click="resetForm">Reset</button>

<button type="button" @click="clearForm">Clear</button>
import Form from './Form.js'

export default {
  
  data() {
    return {
      form: new Form({
        email: 'sample@example.com',
        username: 'sample',
      })
    }
  },
  
  methods: {

    async save() {
      this.form.post('http://httpbin.org/post')
    },
    
    resetForm() {
      this.form.reset()
    },
    
    clearForm() {
      this.form.clear()
    },
    
  }
}
class Form {
constructor (data) {
this._originalData = Object.assign({}, data)
for (let key in data) {
this[key] = data[key]
}
}
reset () {
for (let key in this._originalData) {
this[key] = this._originalData[key]
}
}
clear () {
for (let key in this._originalData) {
this[key] = null
}
}
async submit (method, url) {
const response = await fetch(url, {
method,
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify(this.data),
})
return await response.json()
}
async post (url) {
return await this.submit('POST', url)
}
async put (url) {
return await this.submit('PUT', url)
}
async delete (url) {
return await this.submit('DELETE', url)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment