Vue3获取父组件插槽中子组件索引(自定义步骤条)
功能需求
该图是element-plus的一些步骤条样式,我的需求是每一个步骤条可以点击后跳转到对应的页面,且标题需要和数字水平排列,另外还需自定义每个步骤条的样式,此时便需要使用自定义组件。
另外一个小的需求是,我想实现类似select和option的使用方式,如下图
要达到这样的效果,并且要给每一个步骤添加对于的数字,应该如何实现呢?
代码实现
Step.vue
<script lang="ts">
import { defineComponent, h } from 'vue'
export default defineComponent({
render() {
let children = this.$slots.default && this.$slots.default()
if (children) {
for (let i = 0; i < children.length; i++) {
let props = children[i].props as any
props.index = i
children[i].props = props
}
}
return h('div', { class: 'step-wrapper' }, children)
}
})
</script>
此处先获取插槽中所有的子组件,然后动态给每一个子组件的props属性添加一个inde属性,然后便可在index中使用。
StepItem.vue
<template>
<div class="step-item-wrapper">
<div class="number">{{ index + 1 }}</div>
<div>
<slot></slot>
</div>
<div class="step-line"></div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
props: {
to: {
type: String,
require: true
},
activeClass: {
type: String
},
index: {
type: Number
}
},
setup() {
return {}
}
})
</script>