这个不用高阶组件,可以实现吗

来源:5-28 播放器 高阶 Scroll 组件的实现

flask

2021-12-02

我自己尝试用.vue文件去写,无法监听到scroll事件, scroll.on(‘scroll’)回调有时不会执行

<script lang="ts" >
import Scroll from '@/components/Scroll/index.vue'
import { useStore } from '@/store'
import { watch, nextTick, ref, computed, defineComponent } from 'vue'

export default defineComponent({
  name: 'WrapScroll',
  props: Scroll.props,
  emits: Scroll.emits,
  components: {
    Scroll
  },
  //   render (ctx) {
  //     return h(Scroll, mergeProps({
  //       ref: 'scrollRef'
  //     }, ctx.$props, {
  //       onScroll: (e) => {
  //         ctx.$emit('scroll', e)
  //       }
  //     }), {
  //       default: withCtx(() => {
  //         return [renderSlot(ctx.$slots, 'default')]
  //       })
  //     })
  //   },
  setup () {
    const store = useStore()
    const scrollRef = ref<HTMLElement | null>(null)
    const scroll = computed(() => (scrollRef.value as any).scroll)
    watch(store.state.playList, async () => {
      await nextTick()
      scroll.value.refresh()
    })
    return {
      scroll,
      scrollRef
    }
  },
  methods: {
    emitScroll (e: any) {
      this.$emit('scroll', e)
    }
  }
})

</script>
<template>
  <Scroll
    @scroll="emitScroll"
    ref="scrollRef"
  >
    <slot />
  </Scroll>
</template>

写回答

2回答

qq_汤先生_0

2022-06-07

可以用v-bind="$attrs"这个方法更加简洁 ,vue3的v-bind="$attrs"合并了vue2的v-bind="$attrs"跟v-on="$listeners"

<script setup lang='ts'>

import type Scroll from '../base/scroll/scroll.vue'

import { useMainStore } from '~/stores/main'


const mainStore = useMainStore()

const scrollRef = ref<InstanceType<typeof Scroll>>()


const scroll = computed(() => {

  return scrollRef.value!.scroll

})

const playlist = computed(() => mainStore.playlist)


watch(playlist, async() => {

  await nextTick()

  scroll.value!.refresh()

})


defineExpose({

  scroll,

  scrollRef,

})


</script>

<template>

  <Scroll

    ref="scrollRef"

    v-bind="$attrs"

  >

    <slot />

  </Scroll>

</template>


0
0

ustbhuangyi

2021-12-03

你这写的不对呀,没有把外部传递的 props 透传下去

0
1
flask
好的,谢谢,视频中render函数中的mergeProps就是把外部传递的props透传下去的作用吧,我以为props: Scroll.props这个就可以传递了
2021-12-06
共1条回复

Vue3开发企业级音乐Web App 明星讲师带你学大厂代码

慕课网明星讲师黄轶深度讲解 Vue3.0 ,提升的不止是Vue代码能力

2223 学习 · 1002 问题

查看课程