wifi - 副本.vue 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <template>
  2. <view class="page" :style="{'min-height':h+'px', 'padding-top':mt+'px'}">
  3. <cus-header title='无线局域网' bgColor="transparent"></cus-header>
  4. <view class="content">
  5. <button @click="initWifi">初始化WiFi模块</button>
  6. <button @click="getConnectedWifi">获取已连接WiFi</button>
  7. <button @click="getWifiList">扫描WiFi列表</button>
  8. <view v-if="connectedWifi">
  9. <text>已连接: {{ connectedWifi.SSID }}</text>
  10. <text>信号强度: {{ connectedWifi.level }} dBm</text>
  11. </view>
  12. <view v-for="(wifi, index) in wifiList" :key="index">
  13. <text>{{ wifi.SSID }}</text>
  14. <text>信号: {{ wifi.level }} dBm</text>
  15. <button @click="connectWifi(wifi)">连接</button>
  16. </view>
  17. </view>
  18. </view>
  19. </template>
  20. <script>
  21. export default {
  22. data() {
  23. return {
  24. wifiList: [],
  25. connectedWifi: null
  26. }
  27. },
  28. methods: {
  29. // 初始化WiFi模块
  30. initWifi() {
  31. uni.startWifi({
  32. success: () => {
  33. uni.showToast({ title: 'WiFi模块初始化成功' });
  34. this.startWifiListener();
  35. },
  36. fail: (err) => {
  37. console.error('初始化失败:', err);
  38. }
  39. });
  40. },
  41. // 获取已连接WiFi
  42. getConnectedWifi() {
  43. uni.getConnectedWifi({
  44. success: (res) => {
  45. this.connectedWifi = res.wifi;
  46. },
  47. fail: (err) => {
  48. console.error('获取失败:', err);
  49. }
  50. });
  51. },
  52. // 扫描WiFi列表
  53. getWifiList() {
  54. uni.startWifi({
  55. success: () => {
  56. uni.getWifiList({
  57. success: (res) => {
  58. console.log('获取列表成功');
  59. },
  60. fail: (err) => {
  61. console.error('获取列表失败:', err);
  62. }
  63. });
  64. }
  65. });
  66. },
  67. // 监听WiFi变化
  68. startWifiListener() {
  69. uni.onWifiConnected((res) => {
  70. this.connectedWifi = res.wifi;
  71. });
  72. uni.onGetWifiList((res) => {
  73. this.wifiList = res.wifiList.sort((a, b) => b.level - a.level);
  74. });
  75. },
  76. // 连接指定WiFi
  77. connectWifi(wifi) {
  78. uni.connectWifi({
  79. SSID: wifi.SSID,
  80. password: 'your_password', // 需要实际密码
  81. success: () => {
  82. uni.showToast({ title: '连接成功' });
  83. },
  84. fail: (err) => {
  85. console.error('连接失败:', err);
  86. }
  87. });
  88. }
  89. }
  90. }
  91. </script>
  92. <style scoped lang="less">
  93. .page{
  94. background: #F1F3F5;
  95. box-sizing: border-box;
  96. .content {
  97. padding: 20px;
  98. }
  99. button {
  100. margin: 10px 0;
  101. padding: 8px;
  102. background-color: #007AFF;
  103. color: white;
  104. border-radius: 5px;
  105. }
  106. }
  107. </style>