I'm trying to emit a prop that I modify. I can do that directly with the prop and it works but I get a Vue Warn: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders
So I tried to put the prop in a computed, but the emit executes before the computed is executed.
template:
<input
v-on:keyup="validatedate(localDate)"
v-on:change="emitAnswer(localDate)"
v-model="localDate">
,
computed: {
dateLocal: {
get: function () {
return this.date
}
}
methods: {
emitAnswer: function (date) {
this.$emit('myFunc', date);
}
}
答案 0 :(得分:3)
Since Vue can't guarantee that v-model will be executed before the v-on:change, you can use watchers to only call the emit once the value of the property has been changed in the component, example:
watch {
date() {
this.$emit('myFunc', this.date)
}
}
答案 1 :(得分:0)
首先,我认为您的计算名称错误(“ dateLocal”应为“ localDate”),但我认为这不是问题。
如果设置了值,为什么不在发射前检查内部方法?
shared_from_this
另外,为了更好地实践,您应该对要修改的计算属性使用methods: {
emitAnswer: function (date) {
if (date) {
this.$emit('myFunc', date)
}
}
}
处理程序:
set
希望这对您有所帮助,如果您需要进一步的帮助,请随时回复。
答案 2 :(得分:0)
为避免更改道具,最好定义一个使用道具作为其初始值(source)的本地数据属性:
props: ['date'],
data () {
return {
localDate: this.date
}
}
现在您可以将localDate
数据用作v-model
,并且emitAnswer
方法不需要任何参数:
//template
<input @change="emitAnswer" v-model="localDate">
//script
props: ['date'],
data () {
return {
localDate: this.date
}
},
methods: {
emitAnswer () {
this.$emit('myFunc', this.localDate)
}
}