繁体   English   中英

Vue.js/Nuxt.js - 如何将道具传递给插槽?

[英]Vue.js/Nuxt.js - How to pass props to slots?

所以我有一个具有以下代码的祖父组件:

<template>
  <div>
      <Question qtype="single" qroot="1">
        <Answer qpoints="5" aid="1" qcorrect>Option 1</Answer>
        <Answer qpoints="0" aid="2">Option 2</Answer>
      </Question>
  </div>
</template>
<style>
</style>
<script>
import Question from "~/components/render/Question";
import Answer from "~/components/render/Answer";
export default {
  components: {
    Question,
    Answer
  }
};
</script>

父组件:

<template>
  <div>
        <slot v-bind="$props"></slot>
  </div>
</template>
<style>
</style>
<script>
export default {
  props: ['qtype','qroot']
};
</script>

孩子:

<template>
  <div>
    {{$props}}
    <li style="clear: left;">
      <input v-if="qtype == 'single'" :id="'qid-'+qid" type="radio" :name="qroot" :value="qid" style="float:left" />
      <input v-if="qtype == 'multiple'" :id="'qid-'+qid" type="checkbox" :name="qroot" :value="qid" style="float:left" />
      <label style="float:left;margin-left:5px" :for="'qid-'+qid">
        <slot></slot>
      </label>
    </li>
  </div>
</template>
<style>
</style>
<script>
export default {
   props: ["qtype", "qpoints", "qcorrect", "qroot", "aid"]
};
</script>

我尝试使用 v-bind,像这样 ':qtype="qtype"' 的常规道具传递,但它似乎不起作用。 如何将“qtype”和“qroot”道具传递给孙子组件?

您可以使用Scoped Slots实现您想要的。

首先,我们需要在Question.vue中正确命名道具绑定。 我们slotProps

<!-- Question.vue -->
<slot :slotProps="$props"></slot>

现在让我们在主文件中做所有的魔法。
现在还记得我提到过 Scoped Slots 吗? 使用他们的 API,我们可以做到这一点。 我认为代码不言自明。

<!-- main file -->
<Question qtype="single" qroot="1" v-slot="{ slotProps }">
  <Answer :qtype="slotProps.qtype" :qroot="slotProps.qroot" qpoints="5" aid="1" qcorrect>Option 1</Answer>
  <Answer :qtype="slotProps.qtype" :qroot="slotProps.qoot" qpoints="0" aid="2">Option 2</Answer>
</Question>

免责声明:这只适用于Vue 2.6或更高版本!

不相信它有效? 看看这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM