欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3?setup語法糖中獲取slot插槽的dom對象代碼示例

 更新時間:2024年04月19日 10:03:52   作者:WJP丶  
slot元素是一個插槽出口,標(biāo)示了父元素提供的插槽內(nèi)容將在哪里被渲染,這篇文章主要給大家介紹了關(guān)于vue3?setup語法糖中獲取slot插槽的dom對象的相關(guān)資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下

前言

最近使用vue3開發(fā)項目,需要封裝一個無限滾動的組件,使用scroll組件內(nèi)置插槽接受模板的方式,所以需要在scroll組件內(nèi)獲取到模板渲染后dom元素的寬高。

但是setup語法糖是組件生命周期的beforeCreate和created中,而且經(jīng)過測試,在mounted函數(shù)中的el屬性也是null,所以得出結(jié)論模板的slot.default無法直接獲取, 必須通過 render 方式對 slot 的 vnode 進行渲染,然后在 render 組件中的 mounted 方法中才能獲取到。如下面的例子

容器組件 ScrollView

//ScrollView.vue  scroll容器組件
<script setup lang="ts">
 import { ref, useSlots } from 'vue'
 import createSlot from '../vnode/createSlot'
 const slot = useSlots()
 // 這里獲取到的是默認插槽的vnode,但拿不到對應(yīng)的dom實例
 const defaultSlot = slots.default && slots.default()[0]

 // 自定義template 內(nèi)容mounted事件
 const mountedCallFun = (args)=> {
  console.log('mounted', args)
 }
 // 自定義template 內(nèi)容updated事件
 const updatedCallFun = (args)=> {
  console.log(args)
 }
 // 自定義template 內(nèi)容unMounted卸載事件
 const unmountedCallFun = (args)=> {
  console.log(args)
 }
 const mySlot = createSlot({mountedCallFun, updatedCallFun, unmountedCallFun})
 onMounted(() => {
  // 即使在該組件的mounted鉤子中,這個defaultSlot的$el依然為null
  console.log('defaultSlot', defaultSlot)
 })
</script>

<template>
  <div>
    <mySlot :vnode="defaultSlot"></mySlot>
  </div>
</template>

render函數(shù)渲染slot內(nèi)容的工廠函數(shù) createSlots.ts

通過 vue官方提供的 defineComponent創(chuàng)建一個組件裝載 scrollView組件中的 插槽內(nèi)容:

//createSlots.ts
import { defineComponent, h } from "vue"
type CallFun = (vnodeEl: HTMLElement) => void
type Funs = Record<'mountedCallFun'| 'updatedCallFun'| 'unmountedCallFun', CallFun>
export default ({mountedCallFun, updatedCallFun, unmountedCallFun}: Funs) => {
  return defineComponent({
    props: ['vnode'],
    setup(props, ctx){
      console.log(props, ctx)
    },
    mounted() {
      // console.log(this.$el)
      mountedCallFun(this.$el)
    },
    render(props: any, ctx: any) {
      console.log(props, ctx)
      return props.vnode
    }
  })
}

測試使用 ScrollView組件

<script setup lang="ts">
  import Text from '../components/text.vue'
  import ScrollView from '../components/ScrollView.vue'
</script>

<template>
  <div>
    <ScrollView>
      <h2 >測試使用 ScrollView組件測試使用 ScrollView組件</h2>
      <h2 >測試使用 ScrollView組件測試使用 ScrollView組件</h2>
      <h2 >測試使用 ScrollView組件測試使用 ScrollView組件</h2>
      <h2 >測試使用 ScrollView組件測試使用 ScrollView組件</h2>
    </ScrollView>
  </div>
</template>

總結(jié)  

到此這篇關(guān)于vue3 setup語法糖中獲取slot插槽的dom對象的文章就介紹到這了,更多相關(guān)vue3獲取slot插槽dom對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論