【发布时间】:2018-06-14 10:59:13
【问题描述】:
问题
我有一个接受 id 属性的 BaseFormControl 组件。它将id 属性值设置为<label> 元素上的for 属性值和给定输入上的id 属性值。由于我希望 BaseFormControl 成为可与各种输入类型一起使用的通用组件,因此我将输入作为插槽传递。下面的组件代码:
<script>
export default {
props: {
id: {
type: String,
required: true
}
}
};
</script>
<template>
<div>
<label :for="id">
<slot name="label" />
</label>
<slot
name="input"
:id="id"
/>
</div>
</template>
这种方法的问题是<slot> 没有将任何属性传递给插槽内容,因此:id 根本没有传递给实际输入。
所以我尝试以编程方式设置它:
export default {
props: {
id: {
type: String,
required: true
}
}
created() {
let inputSlot = this.$slots.input;
if (inputSlot) {
inputSlot[0].data.attrs.id = this.id;
}
}
};
在某些情况下它可以完美运行(作为插槽传递的输入在其 HTML 中正确设置了 id 属性),但在其他情况下则不然。特别有趣的是,所有的输入组件(我放在输入槽中的是另一个基本组件,而不是通用的<input> 标签)实际上是用id 正确填充的this.$attrs,但有时它会出现在实际的HTML 中有时不会。
谁能解释一下我的这种行为,告诉我我做错了什么以及如何解决这个问题?
笔
我创建了一个pen 来说明这些概念。唯一的问题是在笔中一切正常。在我的应用中,在页面上的 2 个选择中,只有 1 个正确设置了 id - 另一个在没有 id 的情况下呈现(尽管 id 设置在它的 this.$attrs 中)。
【问题讨论】:
标签: vue.js vue-component