breadcrumb.vue 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <template>
  2. <view v-if="breadcrumbList.length > 0" class="bg-white px-24rpx py-16rpx">
  3. <scroll-view scroll-x class="whitespace-nowrap">
  4. <view class="inline-flex items-center">
  5. <view
  6. class="flex items-center text-28rpx"
  7. :class="breadcrumbList.length > 0 ? 'text-[#1890ff]' : 'text-[#333]'"
  8. @click="handleClick(-1)"
  9. >
  10. <text>全部部门</text>
  11. </view>
  12. <template v-for="(item, index) in breadcrumbList" :key="item.id">
  13. <wd-icon name="arrow-right" size="12px" color="#999" custom-class="mx-8rpx" />
  14. <view
  15. class="flex items-center text-28rpx"
  16. :class="index < breadcrumbList.length - 1 ? 'text-[#1890ff]' : 'text-[#333]'"
  17. @click="handleClick(index)"
  18. >
  19. <text>{{ item.name }}</text>
  20. </view>
  21. </template>
  22. </view>
  23. </scroll-view>
  24. </view>
  25. </template>
  26. <script lang="ts" setup>
  27. import { ref, watch } from 'vue'
  28. interface BreadcrumbItem {
  29. id: number
  30. name: string
  31. }
  32. const props = defineProps<{
  33. modelValue: number
  34. }>()
  35. const emit = defineEmits<{
  36. 'update:modelValue': [value: number]
  37. }>()
  38. const breadcrumbList = ref<BreadcrumbItem[]>([])
  39. /** 监听外部值变化 */
  40. watch(() => props.modelValue, (val) => {
  41. if (val === 0) {
  42. breadcrumbList.value = []
  43. }
  44. })
  45. /** 点击面包屑 */
  46. function handleClick(index: number) {
  47. if (index === -1) {
  48. // 点击"全部部门"
  49. breadcrumbList.value = []
  50. emit('update:modelValue', 0)
  51. } else if (index < breadcrumbList.value.length - 1) {
  52. // 点击中间层级
  53. const item = breadcrumbList.value[index]
  54. breadcrumbList.value = breadcrumbList.value.slice(0, index + 1)
  55. emit('update:modelValue', item.id)
  56. }
  57. }
  58. /** 进入子层级 */
  59. function enter(item: BreadcrumbItem) {
  60. breadcrumbList.value.push(item)
  61. emit('update:modelValue', item.id)
  62. }
  63. /** 返回上一层级 */
  64. function back(): boolean {
  65. if (breadcrumbList.value.length === 0) {
  66. return false
  67. }
  68. breadcrumbList.value.pop()
  69. const lastItem = breadcrumbList.value[breadcrumbList.value.length - 1]
  70. emit('update:modelValue', lastItem?.id ?? 0)
  71. return true
  72. }
  73. /** 重置 */
  74. function reset() {
  75. breadcrumbList.value = []
  76. emit('update:modelValue', 0)
  77. }
  78. defineExpose({ enter, back, reset })
  79. </script>