cwg-link.vue 2.4 KB

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