【问题标题】:Why I get only one element in slot inside v-for?为什么我在 v-for 的插槽中只有一个元素?
【发布时间】:2020-02-15 06:21:58
【问题描述】:

在我的 vue 应用程序代码中,我有一个 swiper 组件。在这个组件内部,我有一个 v-for 和一个插槽。

在父组件 (Foo) 中,我需要通过 ref 捕获我放入插槽的组件 (baz)。问题是它返回只有一个元素而不是像我这样的数组。

如何保持组件的这种形状并且仍然得到我期望的数组?有可能吗?

import Vue from "vue";

Vue.config.productionTip = false;

const Foo = {
  template: `
    <div>
    <swiper :items="items">
    <baz ref="baz"/>
    </swiper>
    </div>
  `,
  data: function() {
    return {
      items: [1, 2, 3, 4, 5]
    };
  },
  mounted: function() {
    this.$nextTick().then(() => {
      console.log({ refs: this.$refs.baz });
    });
  }
};

const Baz = { template: "<div>im baz</div>" };

const Swiper = {
  template: `
    <div class="swiper">
    <div v-for="(item, i) in items" :key="i">
        <slot></slot>
    </div>
    </div>
    `,
  props: ["items"]
};


Vue.component("foo", Foo);
Vue.component("baz", Baz);
Vue.component("swiper", Swiper);

new Vue({
  render: h => h(Foo)
}).$mount("#app");
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"&gt;&lt;/script&gt;

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    你需要改变你的结构。不要在swiper 模板中使用v-for,而是在foo 模板中使用它。让swiper 模板处理仅呈现单个项目。这是您所期望的一个工作示例:https://codesandbox.io/s/jolly-meninsky-qqe6k

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 1970-01-01
      • 2023-01-17
      • 2018-09-26
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多