cwg-link.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <template>
  2. <!-- #ifdef H5 -->
  3. <!-- H5 端:支持普通跳转 / PDF预览 / 文件下载 -->
  4. <a
  5. v-if="isDownload"
  6. class="pdf-link"
  7. :href="url"
  8. :download="downloadName"
  9. target="_blank"
  10. >
  11. <slot v-if="slots['default']"></slot>
  12. <view v-else>{{ t(title) || title }}</view>
  13. </a>
  14. <view
  15. v-else
  16. class="pdf-link"
  17. @click="handleClick"
  18. >
  19. <slot v-if="slots['default']"></slot>
  20. <view v-else>{{ t(title) || title }}</view>
  21. </view>
  22. <!-- #endif -->
  23. <!-- #ifdef APP-PLUS -->
  24. <!-- APP 端:统一点击处理 -->
  25. <view class="pdf-link" @click="handleClick">
  26. <slot v-if="slots['default']"></slot>
  27. <view v-else>{{ t(title) || title }}</view>
  28. </view>
  29. <!-- #endif -->
  30. </template>
  31. <script setup>
  32. import { useSlots } from 'vue'
  33. import { openLocalPdf } from '@/utils/pdf'
  34. import { openExternalUrl } from '@/utils/openExternalUrl'
  35. import { useI18n } from 'vue-i18n'
  36. const { t } = useI18n()
  37. const slots = useSlots()
  38. const props = defineProps({
  39. url: String,
  40. type: {
  41. type: String,
  42. default: 'pdf' // pdf / pdf1 / html / download
  43. },
  44. title: String,
  45. target: String,
  46. // 下载文件名(下载时必填)
  47. downloadName: String
  48. })
  49. // 判断是否是下载类型
  50. const isDownload = props.type === 'download'
  51. const handleClick = () => {
  52. if (!props.url) return
  53. // 下载逻辑(APP端)
  54. if (props.type === 'download') {
  55. startDownload()
  56. return
  57. }
  58. // PDF 预览
  59. if (props.type == 'pdf' || props.type == 'pdf1') {
  60. openLocalPdf(props.url, props.title, props.type)
  61. }
  62. // 外链打开
  63. else if (props.type === 'html') {
  64. openExternalUrl(props.url)
  65. }
  66. }
  67. // APP 端下载方法
  68. const startDownload = () => {
  69. uni.showLoading({ title: '下载中...', mask: true })
  70. uni.downloadFile({
  71. url: props.url,
  72. success: (res) => {
  73. uni.hideLoading()
  74. if (res.statusCode === 200) {
  75. uni.openDocument({
  76. filePath: res.tempFilePath,
  77. fileName: props.downloadName,
  78. success: () => {
  79. uni.showToast({ icon: 'none', title: '下载完成' })
  80. }
  81. })
  82. } else {
  83. uni.showToast({ icon: 'none', title: '下载失败' })
  84. }
  85. },
  86. fail: () => {
  87. uni.hideLoading()
  88. uni.showToast({ icon: 'none', title: '下载链接异常' })
  89. }
  90. })
  91. }
  92. </script>
  93. <style scoped>
  94. .pdf-link {
  95. display: inline-block;
  96. cursor: pointer;
  97. }
  98. </style>