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

全部回复(1)
P粉155832941

如果你真的需要用插槽来做到这一点,那么你就必须这样做 使用 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函数来构建您想要的内容。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号