ホームページ  >  に質問  >  本文

vue3を使用してスロット内のHTMLElementsを取得するにはどうすればよいですか?

<p>現在、レイヤー コンポーネントを公開しているときに問題が発生しました。コードは次のとおりです。</p> <p><em>// Wrapper.vue</em></p> <pre class="brush:php;toolbar:false;"><テンプレート> <slot v-bind="attrs"<</slot> </テンプレート> <script lang="ts"セットアップ> 輸入 { Props の定義、 参照、 時計、 useAttrs、 マウントされた、 アンマウント時、 現在のインスタンスを取得、 「vue」から; const props =defineProps({ 名前: { タイプ: 文字列、デフォルト: "" }、 zIndex: { タイプ: 数値、デフォルト: 0 }, }); const attrs = useAttrs(); const inst = getCurrentInstance(); const オブザーバー = ref(null); 時計( () => [props.zIndex, props.name], () => { setBrothersAttrs(); } ); onMounted(() => { el = inst?.vnode.el; とします。 if (el) { if (!observer.value) observer.value = 新しい MutationObserver(setBrothersAttrs); observer.value.observe(el.parentElement, { childList: true }); } setBrothersAttrs(); }); onUnmounted(() => { if (observer.value) observer.value.disconnect(); }); const setBrothersAttrs = () => { el = inst?.vnode.el; とします。 let Children = el?.parentElement?.children; if (el && Children) { for (let i = 0; i <div class="inner"> <ラッパー名="wrapper2" :z-index="2"> <img class="picture2" /> </ラッパー> </div> <ラッパー名 = "wrapper3" :z-index="3"> <img class="写真3" /> </ラッパー> </ラッパー> </div> </テンプレート> <script lang="ts" セットアップ> 「./Wrapper.vue」から Wrapper をインポートします。 </script></pre> <p><em>// HTML 形式の結果: </em></p> <pre class="brush:php;toolbar:false;"><div class="test"> <img class="picture1" style="z-index: 1" /><!-- Wrapper3 がない場合、"z-index: 3" --> <div class="inner" style="z-index:1"" <img class="picture2" style="z-index: 2" /> </div> <img class="picture3" style="z-index: 1" /><!-- Wrapper3 がない場合、"z-index: 3" --> </div></pre> <ブロック引用> <p>上記のコードに示されているように、Wrapper コンポーネントは空のコンポーネントです。その目的は、slot["default"] 内の HTMLElement の z-index を設定することです。 </p> </blockquote> <p>残念ながら、useSlots()["default"] に子要素が見つかりません。 <strong>そこで、親の childList を突然変異観察者に観察させてみました。 </strong></p> <p>それ自体は問題なく動作します (<em>例の図 1 と図 2 のように</em>)。 <strong>ただし、複数の Wrapper を一緒にラップすると、相互に重なってしまいます (<em>例の画像 3 のように、wrapper3 によって設定された画像 3 の z-index は、wrapper1 によって上書きされます)。 </strong>これは、同じ親を共有するため、親の子は常に同じであることを意味します。 </p> <p>それで、質問は再び「<strong>スロットで HTMLElements を取得する方法</strong>」になります...vuejs の達人が私を助けてくれませんか? </p>
P粉794177659P粉794177659387日前513

全員に返信(1)返信します

  • P粉714890053

    P粉7148900532023-09-02 12:22:06

    これは、Vue レンダリング関数を使用してより簡単に実行できます。 レンダリング スロット

    リーリー リーリー リーリー

    返事
    0
  • キャンセル返事