uni-app基于mixins实现onShareAppMessage统一处理

实现

// Share.ts
import Vue from "vue";
import Component from "vue-class-component";

export interface ShareOptions {
    /** 分享地址,不传则分享当前页面 */
    path?: string;
    /** 分享参数 */
    params?: { [key: string]: any };
    /** 转发标题,不传则默认使用当前小程序的昵称。 */
    title?: string;
    /** 转发显示图片的链接,可以是网络图片路径或本地图片文件路径或相对代码包根目录的图片文件路径。显示图片长宽比是 5:4 */
    imageUrl?: string;
    /** onShareAppMessage回调函数 */
    callback?: () => void;
}

/**
 * @description url追加参数
 *
 * @param url
 * @param data  追加的数据
 */
export const appendQuery = (url: string, data: Record): string => {
    let params = "?";
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            let value = data[key];
            if (typeof value === "object") {
                value = JSON.stringify(value);
            }
            params += `${key}=${value}&`;
        }
    }
    return `${url}${params.slice(0, params.length - 1)}`;
};

// You can declare mixins as the same style as components.
@Component
export class Share extends Vue {
    public shareOptions: ShareOptions = {};

    public async onShareAppMessage() {
        const pages = getCurrentPages();
        const { route } = pages[pages.length - 1];
        const defaultParams = {}; // 默认参数,比如注入分享者的userId
        const {
            path = route as string,
            params = {},
            title,
            imageUrl,
            callback = () => {}
        } = this.shareOptions || {};
        typeof callback === "function" && callback();
        return {
            path: appendQuery(path, { ...defaultParams, ...params }),
            title,
            imageUrl
        };
    }

    created() {
        setTimeout(() => {
            const { query } = uni.getEnterOptionsSync();
            // 获取进入分享页后相关参数,比如获取分享者的userId,然后进行相关操作
        }, 0);
    }
}

调用

@Component({ components: {} })
export default class extends mixins(Share) {
    public shareOptions: ShareOptions = {};

    onLoad(options: Record) {
        this.$set(this.shareOptions, "params", options); // 动态设置
    }
}

你可能感兴趣的:(uni-app基于mixins实现onShareAppMessage统一处理)