【发布时间】:2017-11-09 00:36:38
【问题描述】:
我很难获取父组件的属性对象,动态填充属性以使值在同一组件内可用。
有点难解释,请看下面的例子:
父组件
<script>
export default {
data() {
return {
fields: {},
}
}
}
</script>
子组件
<template>
<select
@change="update()"
v-model="field"
>
<option
v-for="option in options"
:value="option.value"
>
{{ option.name }}
</option>
</select>
</template>
<script>
export default {
props: {
initialOptions: {
type: Array,
required: true
}
},
data() {
return {
field: '',
options: this.initialOptions
}
},
mounted() {
if (
(this.field === undefined || this.field === '') &&
this.options.length > 0
) {
this.field = this.options[0].value;
}
this.update();
},
methods: {
update() {
this.$emit('input', this.field);
}
}
}
</script>
DOM
<parent-component inline-template>
<div>
<child-component>
:initial-options="[{..}, {..}]"
v-model="fields.type_id"
></child-component>
</div>
<div :class="{ dn : fields.type_id == 2 }">
// ...
</div>
</parent-component>
使用 Vue 控制台,我可以看到 fields 对象获取所有子组件模型及其关联值,因为它们在挂载时发出 input,但是由于某些奇怪的原因,:class="{ dn : fields.type_id == 2 }" 没有附加该类dn when the selection changes to 2. Dom 似乎没有反映父组件和子组件之间同步的更改。
关于如何使它工作的任何帮助?
【问题讨论】:
-
你是如何向父
fields添加属性的? -
在子组件上使用
v-model指令并在mounted上使用来自每个子组件的关联值发出input事件。 -
你能展示一下吗?我得到的是
fields开始是一个空对象。如果您错误地添加属性,那么 Vue 将无法检测到更改。 -
在上面的例子中 - 请检查
Child Component部分然后DOM子组件得到v-model。你会看到在mounted上有一个对update()方法的调用,它会发出事件。 -
fields: {}何时/如何获得名为type_id的属性?
标签: vue.js vuejs2 vue-component