如何在子组件中定义的prop中定义插槽中的组件

时间:2018-08-08 13:24:35

标签: vue.js

假设我有三个部分:Alpha,Bravo和Charlie。

看起来像这样:

Alpha.vue

<template>
    <div class="alpha">
        <bravo>
            <template slot="card">
                <charlie></charlie>
            </template>
        </bravo>
    </div>
</template>

Bravo.vue

<template>
    <div class="bravo">
        <slot name="card" v-for="result in results" :result="result"></slot>
    </div>
</template>
<script>
export default {
    data: function() {
        return {
            results: [1, 2, 3]
        }
    }
}
</script>

Charlie.vue

<template>
    <h1>{{ result }}</h1>
</template>
<script>
export default {
    props: [
        'result'
    ]
}
</script>

如何在Alpha的广告位中定义结果道具时将其传递给Charlie?

其背后的想法是Bravo包含许多共享逻辑。有不同的Alpha版本,其中插槽可能包含不同的卡(但始终会有结果道具。)

在运行该代码的那一刻,结果道具没有被解析为Charlie组件,并且发生了未定义的错误(该示例可能有一些错误之处,但我希望它能演示我正在尝试实现的目标。 )

1 个答案:

答案 0 :(得分:0)

我认为这是针对您情况的解决方案

Alpha.vue

<template>
<bravo>
<template slot="card" slot-scope="{ result }">
<charlie :result="result"></charlie>
</template>
</bravo>
</template>

您应该将插槽包装在Bravo.vue中

Documentation