How to get HTMLElements in slot using vue3?
Patricia Arquette
Patricia Arquette 2023-09-01 17:57:52
0
1
495

当我尝试开发 Layer 组件时发生了一些事情。代码如下:

// Wrapper.vue

 

// Test.vue

 

// Results in HTML format:

As shown in the above code, the component Wrapper is an empty component. Its purpose is to set the z-index of HTMLElements in slot["default"].

Unfortunately, I can't find the child element in useSlots()["default"]. So I tried to have a mutation observer observe the parent's childList.

It works fine on its own (like picture 1 and picture 2 in the example). But when multiple Wrapper are wrapped together, it will cover each other (Like picture 3 in the example, the z-index of picture3 set by wrapper3 is overwritten by wrapper1). This means that they share the same parent, so that the parent's children are always the same.

So now the question becomes again "How to get HTMLElements in slot"...can any vuejs guru help me?

Patricia Arquette
Patricia Arquette

reply all (1)
P粉714890053

This can be done more simply using Vue render functions:Rendering slots

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; }
Test
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!