VueUse useShare 分享网页和文件功能

VueUse useShare 分享网页功能,它可以让你从一个网页分享文本、链接\文件到设备上安装的其他应用程序。

代码示例

import { useShare } from '@vueuse/core'

const { share, isSupported } = useShare()
//分析文本和连接
function startShare() {
  share({
    title: 'Hello',
    text: 'Hello my friend!',
    url: location.href,
  })
}

分享文件

<template>
  <button type="button" @click="open()">
    分享文件
  </button>
</template>
<script setup lang="ts">
/*
vueuse 中文文档
https://www.itxst.com/vueuse/tutorial.html
*/
import { useFileDialog } from '@vueuse/core'
import { useShare } from '@vueuse/core'
const { share, isSupported } = useShare();
const { files, open, reset, onChange } = useFileDialog({
  accept: 'image/*', // Set to accept only image files
})

onChange((files) => {
  let arr = [];
  for (let i = 0; i < files.length; i++) {
    arr.push(files[i])
  } 
  share({
    title: '分享文件',
    files: arr
  })
})
</script>

在线例子

在线试一试

类型定义

export interface UseShareOptions {
  title?: string
  files?: File[]
  text?: string
  url?: string
}
/**
 * Reactive Web Share API.
 *
 * @see https://vueuse.org/useShare
 * @param shareOptions
 * @param options
 */
export declare function useShare(
  shareOptions?: MaybeRefOrGetter<UseShareOptions>,
  options?: ConfigurableNavigator,
): {
  isSupported: ComputedRef<boolean>
  share: (overrideOptions?: MaybeRefOrGetter<UseShareOptions>) => Promise<void>
}
export type UseShareReturn = ReturnType<typeof useShare>