我有一个 parent 将 Prop 传递给 child , child 向 parent 发出事件。然而,这并没有完全发挥作用,我不知道为什么。有什么建议吗?
父级:
<template>
<div class="natural-language">
<div class="natural-language-content">
<p class="natural-language-results">
<msm-select :options="payments" :model="isShowingUpdate" />
</p>
</div>
</div>
</template>
<script>
import msmSelect from '../form/dropdown.vue'
export default {
components: {
'msm-select': msmSelect
},
data() {
return {
isShowingUpdate: true,
payments: [
{'value': 'paying anuualy', 'text': 'paying anuualy'},
{'value': 'paying monthly', 'text': 'paying monthly'}
],
}
}
}
</script>
child :
<template>
<div class="form-pseudo-select">
<select :model="flagValue" @change="onChange($event.target.value)">
<option disabled value='Please select'>Please select</option>
<option v-for="(option, index) in options" :value="option.value">{{ option.text }}</option>
</select>
</div>
</template>
<script>
export default {
props: {
options: {
elType: Array
},
isShowingUpdate: {
type: Boolean
}
},
data() {
return {
selected: '',
flagValue: false
}
},
methods: {
onChange(value) {
if (this.selected !== value) {
this.flagValue = true;
} else {
this.flagValue = false;
}
}
},
watch: {
'flagValue': function() {
console.log('it changed');
this.$emit('select', this.flagValue);
}
},
created() {
console.log(this.flagValue);
this.flagValue = this.isShowingUpdate;
}
}
</script>
基本上,当选择框中的选项更改时, bool 标志应该更新。但是,在我的 child 中,我的 isShowingUpdate 得到了未定义。我错过了什么?
最佳答案
这两个组件之间不存在您所说的关系。
您称为父级
的组件实际上是子级...而子级是父级
。
父组件始终是调用另一个组件的组件,在您的情况下:
//Parent component
<template>
...
<msm-select :options="policies" :model="isShowingUpdate" /> << the child
...
</template>
您应该更改两个组件之间的 Prop /事件。
编辑:
您可以编辑:
onChange(value) {
if (this.selected !== value) {
this.flagValue = true;
} else {
this.flagValue = false;
}
}
到一个新的,如下所示:
关于 child :
onChange(value) {
if (this.selected !== value) {
this.flagValue = true;
} else {
this.flagValue = false;
}
this.$emit('flagChanged', this.flagValue)
}
在父级上使用 emit
事件来捕获并调用其他方法:
//HTML part:
<msm-select :options="payments" :model="isShowingUpdate" v-on:flagChanged="actionFlagChanged" />
//JS part:
methods: {
actionFlagChanged () {
//what you want
}
}
我可以给你一些提示
吗?
这不是一个(非常)好的函数名称:
onChange
在 onChange 事件中...尝试类似: updateFlag (更多 语义)。我认为你可以删除 watch 部分并在onChange中执行它 事件
尝试找到一个好的文档/教程(即官方文档)来了解有关家长/ child 沟通的更多信息。
记住添加事件总线导入:
import { EventBus } from './event-bus'
希望对你有帮助!
关于javascript - (VueJS)从子组件更新父数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47072349/