vue实现WiFi列表
Vue实现WiFi列表的步骤
安装依赖 确保项目已安装Vue.js和必要的网络请求库(如axios)。若需模拟数据,可安装Mock.js。
npm install axios mockjs --save
创建WiFi列表组件
新建一个Vue组件(如WifiList.vue),用于展示WiFi列表。组件包含模板、脚本和样式部分。
<template>
<div class="wifi-list">
<h3>可用WiFi网络</h3>
<ul>
<li v-for="wifi in wifiList" :key="wifi.ssid">
{{ wifi.ssid }} (信号强度: {{ wifi.signal }}%)
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
wifiList: []
};
},
mounted() {
this.fetchWifiList();
},
methods: {
async fetchWifiList() {
try {
const response = await axios.get('/api/wifi/list');
this.wifiList = response.data;
} catch (error) {
console.error('获取WiFi列表失败:', error);
}
}
}
};
</script>
<style scoped>
.wifi-list ul {
list-style-type: none;
padding: 0;
}
.wifi-list li {
padding: 8px;
border-bottom: 1px solid #eee;
}
</style>
模拟API数据
若后端API未就绪,可使用Mock.js模拟数据。在项目入口文件(如main.js)中添加以下代码:

import Mock from 'mockjs';
Mock.mock('/api/wifi/list', 'get', {
'list|5-10': [{
'ssid': '@word(3,8)',
'signal|50-100': 100
}]
});
调用真实API
若后端API已就绪,替换fetchWifiList方法中的URL为真实接口地址,并确保处理可能的认证和错误。
async fetchWifiList() {
try {
const response = await axios.get('https://your-api-endpoint.com/wifi', {
headers: { 'Authorization': 'Bearer your-token' }
});
this.wifiList = response.data;
} catch (error) {
console.error('获取WiFi列表失败:', error);
}
}
优化用户体验 添加加载状态和错误提示,提升用户体验。更新组件数据和方法:

<script>
export default {
data() {
return {
wifiList: [],
isLoading: false,
error: null
};
},
methods: {
async fetchWifiList() {
this.isLoading = true;
this.error = null;
try {
const response = await axios.get('/api/wifi/list');
this.wifiList = response.data;
} catch (error) {
this.error = '无法加载WiFi列表,请重试。';
} finally {
this.isLoading = false;
}
}
}
};
</script>
响应式设计 通过CSS媒体查询确保列表在不同设备上显示良好。更新样式部分:
@media (max-width: 600px) {
.wifi-list li {
font-size: 14px;
}
}
自动刷新 通过定时器或WebSocket实现列表自动更新。在组件中添加以下逻辑:
mounted() {
this.fetchWifiList();
this.interval = setInterval(this.fetchWifiList, 30000);
},
beforeDestroy() {
clearInterval(this.interval);
}






