SAnchor2.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const n = `<template>
  2. <a-anchor
  3. :affix="false"
  4. showInkInFixed
  5. :targetOffset="10"
  6. :getContainer="getContainer"
  7. @click="handleAnchorClick"
  8. :items="anchors"
  9. />
  10. </template>
  11. <script setup>
  12. import { nextTick, onMounted, ref } from 'vue'
  13. defineOptions({ name: 'SAnchor' })
  14. const props = defineProps({
  15. // 监听的滚动容器元素(不传则监听 window)
  16. el: {
  17. type: String,
  18. default: 'body'
  19. }
  20. })
  21. const anchors = ref([])
  22. /** 锚点 */
  23. function getItemAnchor () {
  24. const elms = document.querySelectorAll(
  25. '.s-collapses .s-collapses-item .s-collapses-item-title'
  26. )
  27. if (elms.length > 0) {
  28. elms.forEach((i) => {
  29. anchors.value.push({
  30. el: i,
  31. key: i.id,
  32. href: \`#\${i.id}\`,
  33. title: i.lastChild.innerText
  34. })
  35. })
  36. }
  37. }
  38. function initRightNav () {
  39. getItemAnchor()
  40. setTimeout(() => {
  41. anchors.value = []
  42. getItemAnchor()
  43. }, 500)
  44. }
  45. function handleAnchorClick (e, link) {
  46. e.preventDefault()
  47. const i = anchors.value.find((i) => i.href === link.href)
  48. i?.el?.scrollIntoView({ block: 'start', behavior: 'smooth' })
  49. }
  50. function getContainer () {
  51. if (props.el === 'el') {
  52. return document.getElementById('form-container')
  53. }
  54. return document.querySelector(\`.\${props.el}\`)
  55. }
  56. onMounted(() => {
  57. nextTick(() => {
  58. initRightNav()
  59. })
  60. })
  61. <\/script>
  62. `;
  63. export {
  64. n as default
  65. };