简体   繁体   English

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

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

So i have one grandparent component which has this code:所以我有一个具有以下代码的祖父组件:

<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>

Parent component:父组件:

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

Child:孩子:

<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>

I tried to use v-bind, regular prop passing like this ':qtype="qtype"' but it doesn't seem to work.我尝试使用 v-bind,像这样 ':qtype="qtype"' 的常规道具传递,但它似乎不起作用。 How can i pass "qtype" and "qroot" props to the grandchild component?如何将“qtype”和“qroot”道具传递给孙子组件?

You can achieve what you desire using Scoped Slots .您可以使用Scoped Slots实现您想要的。

First of all we need properly name the prop binding in Question.vue .首先,我们需要在Question.vue中正确命名道具绑定。 Let's call call it slotProps for now.我们slotProps

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

Now let's do all the magic in the main file.现在让我们在主文件中做所有的魔法。
Now remember how I mentioned the Scoped Slots?现在还记得我提到过 Scoped Slots 吗? Using theirs API we can do this.使用他们的 API,我们可以做到这一点。 I reckon the codes speaks for itself.我认为代码不言自明。

<!-- 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>

Disclaimer : this works only with Vue 2.6 or higher!免责声明:这只适用于Vue 2.6或更高版本!

Not convinced it works?不相信它有效? Check this out.看看这个

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

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