使用 Vue 渲染函数可以更简单地完成:渲染槽
const { createApp, h } = Vue; const Wrapper = { props: { name: { type: String, default: "" }, zIndex: { type: Number, default: 0 }, }, setup(props, { slots }) { let children = slots.default(); if (children) { for (let i = 0; i < children.length; i++) { children[i].props.style = `z-index: ${props.zIndex}`; } } return () => slots.default() } } const App = { components: { Wrapper } } const app = createApp(App) const vm = app.mount('#app')
#app { line-height: 2; } [v-cloak] { display: none; }
<div id="app" v-cloak> <div class="test"> Test <Wrapper name="wrapper1" :z-index="1"> <img class="picture1" /> <div class="inner"> <Wrapper name="wrapper2" :z-index="2"> <img class="picture2" /> </Wrapper> </div> <Wrapper name="wrapper3" :z-index="3"> <img class="picture3" /> </Wrapper> </Wrapper> </div> </div> <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
使用 Vue 渲染函数可以更简单地完成:渲染槽