Vue.js event handler demo for form elements
Each form element is a child component that passes event back to parent component with the updated value
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<body>
<div id="app"></div>
</body>
CSS
body {
margin: 20px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
.my-text-input {
padding: 10px 20px;
}
input {
padding: 5px 10px;
border: 1px solid #DDD;
}
.result {
margin-top: 20px;
padding-top: 20px;
border-top: 1px solid #DDD;
}
JavaScript
Vue.component('text-input', {
props: ["value"],
template: `
<input type="text" v-model="textFieldValue">
`,
computed: {
textFieldValue: {
get: function() {
return this.value
},
set: function(newValue) {
// Send newValue to parent component via $emit("change")
this.$emit("change", newValue);
}
}
}
});
Vue.component('my-app-form', {
template: `
<div class="my-app-form">
<div class="my-text-input">
Name: <text-input :value="userInfo.name" @change="alterProperty('name', $event)"></text-input>
</div>
<div class="my-text-input">
Email: <text-input :value="userInfo.email" @change="alterProperty('email', $event)"></text-input>
</div>
<div class="result">Result: userInfo = {{userInfo}}</div>
</div>
`,
data: function() {
return {
userInfo: {
name: "",
email: ""
}
}
},
methods: {
alterProperty: function(propToChange, newValue) {
this.userInfo[propToChange] = newValue;
}
}
});
new Vue({
el: '#app',
template: `
<div>
<my-app-form></my-app-form>
</div>
`
});