Reputation: 1
I'm developing custom components on vuejs and want to reuse one component into other, how can I manage state child component from parent?
I'm trying to discover correct way of communication between components and got a situation when custom-input component doesn't change value.
For example, when I type some text into input, a text is changed in both places ({{testData}}
and input
as well), but when I click by button I expected that the value will changed in both places as well, but it doesn't work. Could somebody look the code below and explain what I do wrong?
<div id="app">
<custom v-model="testData">content</custom>
{{testData}}
</div>
Vue.component('customInput', {
template: '
<div>
<input type="text" :value="textValue" @input="doEvent($event)">
</div>',
props: ['value'],
data: function() {
return {
textValue: this.value
};
},
methods: {
doEvent(event) {
this.$emit("input", event.target.value);
}
}
});
Vue.component('Custom', {
template: '
<div>
<button @click="changeData()">Chnage Data</button>
<custom-input v-model="textValue" @input="doEvent()"/>
</div>',
props: ['value'],
data: function() {
return {
textValue: this.value
};
},
methods: {
doEvent() {
this.$emit("input", this.textValue);
},
changeData() {
this.textValue = 'Data has chaged';
this.doEvent();
}
}
});
new Vue({
el: '#app',
data: {
testData: "test data"
}
});
I expect that when I typed or change text by clicking the button the data will change in both places.
Upvotes: 0
Views: 70
Reputation: 562
Your code worked perfectly! You just forgot to add backticks instead of single quotes in your template. Using backticks, you can insert newlines. With single or double quotes, you must write everything on oneline :)
Vue.component('customInput', {
template: `
<div>
<input type="text" :value="textValue" @input="doEvent($event)">
</div>`,
props: ['value'],
data: function() {
return {
textValue: this.value
};
},
methods: {
doEvent(event) {
this.$emit("input", event.target.value);
}
}
});
Vue.component('Custom', {
template: `
<div>
<button @click="changeData()">Chnage Data</button>
<custom-input v-model="textValue" @input="doEvent()"/>
</div>`,
props: ['value'],
data: function() {
return {
textValue: this.value
};
},
methods: {
doEvent() {
this.$emit("input", this.textValue);
},
changeData() {
this.textValue = 'Data has chaged';
this.doEvent();
}
}
});
new Vue({
el: '#app',
data: {
testData: "test data"
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<custom v-model="testData">content</custom>
{{testData}}
</div>
Upvotes: 0