响应式 Web Share API。浏览器提供了可以分享文本或文件内容的功能。
share 方法必须在用户手势(例如按钮点击)之后调用。例如,它不能在页面加载时直接调用。这是为了帮助防止滥用。
VueUse 中的 useShare 是一个用于实现 Web Share API 功能的组合式函数,允许开发者轻松调用设备原生分享功能。该函数主要特性包括:
- 自动检测浏览器是否支持 navigator.share API
- 提供 share() 方法触发分享对话框,支持标题、文本和URL等参数
- 返回 isSupported 响应式引用,用于兼容性检查
Demo
使用
import { useShare } from '@vueuse/core'
const { share, isSupported } = useShare()
function startShare() {
share({
title: 'Hello',
text: 'Hello my friend!',
url: location.href,
})
}
传递源 ref
你可以传递一个 ref 给它,源 ref 的更改将反映到你的共享选项。
import { ref } from 'vue'
const shareOptions = ref<ShareOptions>({ text: 'foo' })
const { share, isSupported } = useShare(shareOptions)
shareOptions.value.text = 'bar'
share()
类型声明
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>