Auto generate form model
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.3/vue.js"></script>
<div id="app">
<output>{{ t}}</output>
<form action="#">
<auto-define v-model="user">
<input name="first_name" placeholder="first_name">
<input name="last_name" placeholder="last_name">
<input name="username" placeholder="username">
</auto-define>
<button type="button" @click="k">Reset</button> (this does not propagate to input fields...)
</form>
</div>
CSS
input {
display: block;
margin-bottom: 5px;
}
output {
display: block;
margin-bottom: 10px;
}
Babel + JSX
const AutoDefine = {
props: ['value'],
methods: {
bridgeInput(key, event) {
this.$emit('input', Object.assign({}, this.value, {
[key]: event.target.value
}))
}
},
render (h) {
const slots = this.$slots && this.$slots.default
if (!slots) return h()
slots.forEach(s => {
if (!s.data || !s.data.attrs || !s.data.attrs.name) return
const name = s.data.attrs.name
s.data.domProps = {
value: this.value[name]
},
s.data.on = {
input: event => {
this.bridgeInput(name, event)
}
}
})
return h('div', slots)
}
}
new Vue({
el: '#app',
data: {
t:'',
user: {}
},
methods:{
k(){
return{
t:this.user.push(this.json);
} }
},
computed: {
json() {
var self=this
return JSON.stringify(self.user)
}
},
components: { AutoDefine }
})