wd-index-anchor.vue 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <template>
  2. <!-- #ifdef MP-DINGTALK -->
  3. <view :class="`wd-index-anchor-ding ${isSticky ? 'is-sticky' : ''}`">
  4. <!-- #endif -->
  5. <view :class="`wd-index-anchor ${isSticky ? 'is-sticky' : ''} ${customClass}`" :style="customStyle" :id="indexAnchorId">
  6. <slot>
  7. {{ index }}
  8. </slot>
  9. </view>
  10. <!-- #ifdef MP-DINGTALK -->
  11. </view>
  12. <!-- #endif -->
  13. </template>
  14. <script setup lang="ts">
  15. import { indexAnchorProps } from './type'
  16. import { onMounted, getCurrentInstance, ref, computed } from 'vue'
  17. import { indexBarInjectionKey } from '../wd-index-bar/type'
  18. import { getRect, isDef, uuid } from '../common/util'
  19. import { useParent } from '../composables/useParent'
  20. const props = defineProps(indexAnchorProps)
  21. const { parent: indexBar } = useParent(indexBarInjectionKey)
  22. const indexAnchorId = ref<string>(`indexBar${uuid()}`)
  23. const { proxy } = getCurrentInstance()!
  24. const top = ref<number>(0)
  25. const isSticky = computed(() => {
  26. return indexBar && indexBar.props.sticky && indexBar.anchorState.activeIndex === props.index
  27. })
  28. function getInfo() {
  29. getRect(`#${indexAnchorId.value}`, false, proxy).then((res) => {
  30. if (isDef(indexBar)) {
  31. top.value = Math.floor(res.top!)
  32. }
  33. })
  34. }
  35. onMounted(() => {
  36. getInfo()
  37. })
  38. defineExpose({
  39. top
  40. })
  41. </script>
  42. <style lang="scss" scoped>
  43. @import './index.scss';
  44. </style>