首页  >  问答  >  正文

更改数组索引以显示下一张幻灯片

<p><pre class="brush:php;toolbar:false;"><template> <div class="carousel"> <slot></slot> <button @click="index++">Next</button> </div> </template> <script setup> import { useSlots, onMounted, onUpdated, ref} from 'vue'; const slots = useSlots() const index = ref(0) onMounted(() => { const defaultSlotElements = slots.default() console.log(`My default slot has ${defaultSlotElements.length} elements.`) }), onUpdated(() =>{ console.log(defaultSlotElements[index]) } ) </script></pre> <p>我正在尝试创建基于插槽的轮播。感谢前一个关于堆栈溢出的人,他帮助我弄清楚了如何提取插槽数组。现在,我正在处理另一个问题。为了创建轮播,我必须以某种方式更改数组中元素的索引,这样我就可以移动到轮播的下一张幻灯片。后来我必须将它注入到我的幻灯片组件中,让 V-show 渲染默认为 0 的当前插槽。但是索引的值会被更改索引的 v-on 指令更改,因此它选择数组中的下一个或上一个槽。我知道我在 vue 中选择了一个复杂的主题,但我不想使用基于图像数组的更简单版本的轮播,因为我无法在其中添加另一个组件。</p> <p>事实证明,我不能简单地通过更改索引<code>arr[index]</code>来选择数组中的下一个对象。</p>
P粉777458787P粉777458787387 天前579

全部回复(1)我来回复

  • P粉155832941

    P粉1558329412023-09-02 12:37:55

    如果你真的需要用插槽来做到这一点,那么你就必须这样做 使用 Vue 渲染函数和 JSX

    <script setup>
    import { useSlots, onMounted, onUpdated, ref, h} from 'vue';
    
    const slots = useSlots()
    const index = ref(0)
    const current = ref(null)
    onMounted(() => {
      const defaultSlotElements = slots.default()
      current.value = defaultSlotElements[0]
    }),
    onUpdated(() =>{
        console.log(defaultSlotElements[index])
        }
    )  
    const render = () => {
        return h('div', { class: 'carousel'}, [
        h('p', `My default slot has ${slots.default().length} elements.`),
        h('div', slots.default()[index.value]),
        h('p', `Picture ${ index.value + 1 }`),
        h('button', { onClick: () => { 
          index.value = index.value + 1 == slots.default().length ? 0 : index.value + 1
        } }, 'Next')
      ]);
    };
    </script>
    
    <template>
        <render />
    </template>

    这是工作证监会游乐场

    更新

    渲染函数可以与自定义组件一起使用。

    这里尝试构建您的 结构。

    SFC 游乐场

    我没有看到任何其他方法可以使用默认插槽而不是使用render函数来构建您想要的内容。

    回复
    0
  • 取消回复