Currently, I am in the process of developing a TypeScript class to manage form submissions and handle server errors:
export default class Form<Model> {
private readonly original: Model
private changes: Partial<Model>
constructor(data: Model) {
this.original = data
Object.keys(this.original).forEach(key => this.initialiseData(key))
}
private initialiseData(key) {
Object.defineProperty(this, key, {
get: () => this.data[key],
set: (value) => this.changes[key] = value
}
}
get data(): Model {
return Object.assign({}, this.original, this.changes)
}
post(url: string) {
// logic for posting data
}
}
In Vue components, the class would be utilized as follows:
import { Component, Vue } from 'vue-property-decorator'
import Form from '~/src/vform'
interface LoginForm {
email: string
password: string
}
@Component
export default class LoginView extends Vue {
form: Form<LoginForm> = new Form<LoginForm>({
email: '',
password: ''
})
async submit() {
await this.form.post('/auth/login')
}
}
The functionality works correctly - I can input data into the form and send it to the server. However, an issue arises with reactivity within Vue.js. Since the properties do not exist on the Form
class, the data is not picked up by v-model
until it changes.
This mainly becomes problematic when displaying data from the form on the screen. At present, I can manage with this limitation, but I am exploring ways to make Vue recognize the reactive properties on my Form
class or achieve similar functionality without compromising the type system.