Files
hzdyjs/mobile/src/components/WeChatDemo.vue
T

555 lines
18 KiB
Vue

<template>
<view class="wechat-demo">
<u-card title="微信JS-SDK功能演示" :show-head="true" margin="20rpx">
<view slot="body">
<!-- 初始化状态 -->
<view class="status-section">
<u-row>
<u-col span="6">
<text class="label">初始化状态:</text>
</u-col>
<u-col span="6">
<u-tag
:text="isInitialized ? '已初始化' : '未初始化'"
:type="getInitStatusType(isInitialized)"
/>
</u-col>
</u-row>
<u-row style="margin-top: 20rpx">
<u-col span="6">
<text class="label">微信环境:</text>
</u-col>
<u-col span="6">
<u-tag
:text="isWeChatEnv ? '微信浏览器' : '非微信环境'"
:type="getWeChatEnvType(isWeChatEnv)"
/>
</u-col>
</u-row>
</view>
<!-- 功能按钮区域 -->
<view class="button-section">
<u-button
@click="initWeChatSDK"
type="primary"
:loading="isInitializing"
:disabled="isInitialized"
style="margin-bottom: 20rpx"
>
{{ isInitializing ? '初始化中...' : '初始化微信SDK' }}
</u-button>
<u-divider text="分享功能" />
<u-row gutter="20">
<u-col span="6">
<u-button
@click="shareToTimeline"
type="success"
:disabled="!isInitialized"
size="small"
>
分享朋友圈
</u-button>
</u-col>
<u-col span="6">
<u-button
@click="shareToFriends"
type="success"
:disabled="!isInitialized"
size="small"
>
分享给朋友
</u-button>
</u-col>
</u-row>
<u-divider text="扫码功能" />
<u-button
@click="scanQRCode"
type="warning"
:disabled="!isInitialized"
style="margin-bottom: 20rpx"
>
<u-icon name="scan" style="margin-right: 10rpx" />
扫一扫
</u-button>
<u-divider text="图片功能" />
<u-row gutter="20">
<u-col span="6">
<u-button
@click="chooseImage"
type="info"
:disabled="!isInitialized"
size="small"
>
选择图片
</u-button>
</u-col>
<u-col span="6">
<u-button
@click="previewImages"
type="info"
:disabled="!isInitialized || selectedImages.length === 0"
size="small"
>
预览图片
</u-button>
</u-col>
</u-row>
<!-- 选中的图片展示 -->
<view v-if="selectedImages.length > 0" class="image-preview">
<u-divider text="已选择的图片" />
<view class="image-grid">
<view
v-for="(image, index) in selectedImages"
:key="index"
class="image-item"
@click="previewImage(image, index)"
>
<image :src="image" mode="aspectFill" />
</view>
</view>
</view>
<u-divider text="地理位置" />
<u-row gutter="20">
<u-col span="6">
<u-button
@click="getLocation"
type="primary"
:disabled="!isInitialized"
size="small"
>
获取位置
</u-button>
</u-col>
<u-col span="6">
<u-button
@click="openLocation"
type="primary"
:disabled="!isInitialized || !currentLocation"
size="small"
>
打开地图
</u-button>
</u-col>
</u-row>
<!-- 位置信息展示 -->
<view v-if="currentLocation" class="location-info">
<u-divider text="当前位置信息" />
<text class="location-text">
纬度: {{ currentLocation.latitude.toFixed(6) }}
</text>
<text class="location-text">
经度: {{ currentLocation.longitude.toFixed(6) }}
</text>
<text class="location-text">精度: {{ currentLocation.accuracy }}米</text>
</view>
<u-divider text="设备信息" />
<u-button
@click="getNetworkType"
type="default"
:disabled="!isInitialized"
style="margin-bottom: 20rpx"
>
获取网络状态
</u-button>
<u-divider text="其他功能" />
<u-row gutter="20">
<u-col span="4">
<u-button
@click="checkJsApi"
type="default"
:disabled="!isInitialized"
size="small"
>
检查接口
</u-button>
</u-col>
<u-col span="4">
<u-button
@click="closeWindow"
type="error"
:disabled="!isInitialized"
size="small"
>
关闭窗口
</u-button>
</u-col>
<u-col span="4">
<u-button @click="clearResults" type="default" size="small">
清空结果
</u-button>
</u-col>
</u-row>
</view>
<!-- 结果展示区域 -->
<view v-if="lastResult" class="result-section">
<u-divider text="操作结果" />
<view class="result-content">
<text class="result-text">{{ lastResult }}</text>
</view>
</view>
</view>
</u-card>
</view>
</template>
<script>
import weChatSDK from '@/utils/wechat.js';
export default {
name: 'WeChatDemo',
data() {
return {
isInitialized: false,
isInitializing: false,
isWeChatEnv: false,
selectedImages: [],
currentLocation: null,
lastResult: '',
shareData: {
title: '智慧校园移动应用',
desc: '基于uni-app的校园管理系统',
link: window.location.href,
imgUrl: 'https://example.com/logo.png', // 替换为实际的分享图标
},
};
},
mounted() {
this.checkWeChatEnvironment();
},
methods: {
/**
* 检查微信环境
*/
checkWeChatEnvironment() {
this.isWeChatEnv = weChatSDK.isWeChatBrowser();
console.log('🔍 微信环境检查:', this.isWeChatEnv);
},
/**
* 初始化微信SDK
*/
async initWeChatSDK() {
if (!this.isWeChatEnv) {
this.showResult('❌ 当前不在微信浏览器环境中');
return;
}
this.isInitializing = true;
try {
await weChatSDK.init({
debug: process.env.NODE_ENV === 'development',
});
this.isInitialized = true;
this.showResult('✅ 微信JS-SDK初始化成功');
} catch (error) {
console.error('初始化失败:', error);
this.showResult(`❌ 初始化失败: ${error.message}`);
} finally {
this.isInitializing = false;
}
},
/**
* 分享到朋友圈
*/
async shareToTimeline() {
try {
await weChatSDK.shareTimeline(this.shareData);
this.showResult('✅ 朋友圈分享配置成功');
} catch (error) {
this.showResult(`❌ 朋友圈分享失败: ${error.message}`);
}
},
/**
* 分享给朋友
*/
async shareToFriends() {
try {
await weChatSDK.shareAppMessage(this.shareData);
this.showResult('✅ 朋友分享配置成功');
} catch (error) {
this.showResult(`❌ 朋友分享失败: ${error.message}`);
}
},
/**
* 扫一扫
*/
async scanQRCode() {
try {
const result = await weChatSDK.scanQRCode();
this.showResult(`✅ 扫码成功: ${result.resultStr}`);
} catch (error) {
this.showResult(`❌ 扫码失败: ${error.message}`);
}
},
/**
* 选择图片
*/
async chooseImage() {
try {
const result = await weChatSDK.chooseImage({
count: 3,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
});
this.selectedImages = result.localIds;
this.showResult(`✅ 选择图片成功,共${result.localIds.length}张`);
} catch (error) {
this.showResult(`❌ 选择图片失败: ${error.message}`);
}
},
/**
* 预览所有图片
*/
async previewImages() {
if (this.selectedImages.length === 0) {
this.showResult('❌ 请先选择图片');
return;
}
try {
await weChatSDK.previewImage({
current: this.selectedImages[0],
urls: this.selectedImages,
});
} catch (error) {
this.showResult(`❌ 预览图片失败: ${error.message}`);
}
},
/**
* 预览单张图片
*/
async previewImage(imageUrl, index) {
try {
await weChatSDK.previewImage({
current: imageUrl,
urls: this.selectedImages,
});
} catch (error) {
this.showResult(`❌ 预览图片失败: ${error.message}`);
}
},
/**
* 获取地理位置
*/
async getLocation() {
try {
const result = await weChatSDK.getLocation();
this.currentLocation = result;
this.showResult(
`✅ 获取位置成功: ${result.latitude.toFixed(6)}, ${result.longitude.toFixed(
6,
)}`,
);
} catch (error) {
this.showResult(`❌ 获取位置失败: ${error.message}`);
}
},
/**
* 打开地图
*/
async openLocation() {
if (!this.currentLocation) {
this.showResult('❌ 请先获取位置信息');
return;
}
try {
await weChatSDK.openLocation({
latitude: this.currentLocation.latitude,
longitude: this.currentLocation.longitude,
name: '当前位置',
address: '通过微信JS-SDK获取的位置',
scale: 16,
});
} catch (error) {
this.showResult(`❌ 打开地图失败: ${error.message}`);
}
},
/**
* 获取网络状态
*/
async getNetworkType() {
try {
const result = await weChatSDK.getNetworkType();
this.showResult(`✅ 网络状态: ${result.networkType}`);
} catch (error) {
this.showResult(`❌ 获取网络状态失败: ${error.message}`);
}
},
/**
* 检查JS接口支持
*/
async checkJsApi() {
try {
const testApis = [
'chooseImage',
'scanQRCode',
'getLocation',
'updateAppMessageShareData',
];
const result = await weChatSDK.checkJsApi(testApis);
let message = '接口支持情况:\n';
testApis.forEach((api) => {
message += `${api}: ${result.checkResult[api] ? '✅支持' : '❌不支持'}\n`;
});
this.showResult(message);
} catch (error) {
this.showResult(`❌ 检查接口失败: ${error.message}`);
}
},
/**
* 关闭窗口
*/
closeWindow() {
uni.showModal({
title: '确认',
content: '确定要关闭当前窗口吗?',
success: (res) => {
if (res.confirm) {
weChatSDK.closeWindow();
}
},
});
},
/**
* 清空结果
*/
clearResults() {
this.lastResult = '';
this.selectedImages = [];
this.currentLocation = null;
},
/**
* 显示操作结果
*/
showResult(message) {
this.lastResult = message;
console.log('📝 操作结果:', message);
// 显示toast提示
const isSuccess = message.includes('✅');
uni.showToast({
title: isSuccess ? '操作成功' : '操作失败',
icon: isSuccess ? 'success' : 'none',
duration: 2000,
});
},
// 获取初始化状态标签类型
getInitStatusType(isInitialized) {
return isInitialized ? 'success' : 'warning';
},
// 获取微信环境标签类型
getWeChatEnvType(isWeChatEnv) {
return isWeChatEnv ? 'success' : 'error';
},
},
};
</script>
<style lang="scss" scoped>
.wechat-demo {
padding: 20rpx;
.status-section {
margin-bottom: 40rpx;
padding: 20rpx;
background-color: #f8f9fa;
border-radius: 10rpx;
.label {
font-weight: bold;
color: #333;
}
}
.button-section {
margin-bottom: 40rpx;
}
.image-preview {
margin-top: 30rpx;
.image-grid {
display: flex;
flex-wrap: wrap;
gap: 20rpx;
.image-item {
width: 200rpx;
height: 200rpx;
border-radius: 10rpx;
overflow: hidden;
border: 2rpx solid #e6e6e6;
image {
width: 100%;
height: 100%;
}
}
}
}
.location-info {
margin-top: 30rpx;
padding: 20rpx;
background-color: #f0f8ff;
border-radius: 10rpx;
.location-text {
display: block;
margin-bottom: 10rpx;
color: #666;
font-size: 28rpx;
}
}
.result-section {
margin-top: 40rpx;
.result-content {
padding: 20rpx;
background-color: #f5f5f5;
border-radius: 10rpx;
border-left: 4rpx solid #409eff;
.result-text {
color: #333;
font-size: 28rpx;
line-height: 1.6;
white-space: pre-line;
}
}
}
}
</style>