Vue.js / Nuxt.js-如何将道具传递到广告位?

时间:2020-02-06 04:06:15

标签: javascript vuejs2 nuxt.js

所以我有一个祖父母组件,其代码如下:

<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”道具传递给孙子组件?

1 个答案:

答案 0 :(得分:1)

您可以使用Scoped Slots来实现自己的目标。

首先,我们需要在Question.vue中正确命名prop绑定。现在我们称它为slotProps

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

现在让我们来完成主文件中的所有魔术操作。
现在还记得我是怎么提到作用域插槽的吗?使用他们的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或更高版本!

不确信这行得通吗?检出this