0
In child, watch the email
property.
{
props: ['email'],
data() {return {d_email: this.email},
watch:{ email(newEmail){ this.d_email = email }}
}
Using the watched value, your local email variable will be updated whenever the parent changes.
0
To fire an event that the parent will pick up you need to add the link to the child component like:
<child :email="email" v-on:updateemail="setemail"></child>
Where updateemail
is the name of the event and setemail
is a method on the parent that gets called when the event is fired.
In the child you should make d_email
a computed property like this:
computed: {
d_email: function(){ return this.email }
}
With that it should update when the parent updates the prop.
Putting it all together will give you something like this:
<html>
<head>
<script src=" https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<parent></parent>
</div>
<script>
Vue.component('parent', {
template: '<child :email="email" v-on:updateemail="setemail"></child>',
data: function(){
return {
email: "initial@example.org"
}
},
methods: {
setemail: function(e){
console.log("email changed to: ", e)
this.email = e
}
}
});
Vue.component('child', {
template: '<input id="emailinput" type="text" v-model="d_email" v-on:input="updateemail">',
props: ['email'],
methods: {
updateemail: function(e) {
this.$emit("updateemail", e.target.value)
}
},
computed: {
d_email: function(){ return this.email }
}
});
new Vue({
el:'#app',
});
</script>
</body>
</html>
Watch the console and you will see the parents email property getting updated as the user types. If this is hitting a server, you’ll probably want the event to fire when the user submits rather than types, but that’s a trivial change.