Appearance
实现 IpQuery 工具
分类:education | 标签:IP、网络、查询、工具 在线查询公网IP地址,显示地理位置、运营商、时区等详细信息,支持历史记录
2.1 功能说明
在线查询公网IP地址,显示地理位置、运营商、时区等详细信息,支持历史记录
2.2 代码实现
2.2.1 组件结构
本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-input、el-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。
2.2.2 核心逻辑概览
<script setup> 中定义的主要函数/方法:
queryIp()copyIp()goBack()
2.2.3 关键实现代码
以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。
vue
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Refresh, DocumentCopy } from '@element-plus/icons-vue'
interface IpInfo {
query?: string
ip?: string
}
const router = useRouter()
const loading = ref(false)
const error = ref('')
const ipInfo = ref<IpInfo | null>(null)
const queryIp = async () => {
loading.value = true
error.value = ''
try {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 10000)
const response = await fetch('/simple/getip', {
signal: controller.signal
})
clearTimeout(timeoutId)
if (!response.ok) {
throw new Error(`HTTP ${response.status}`)
}
const data = await response.json()
ipInfo.value = {
query: data.ip,
ip: data.ip
}
} catch (err: any) {
console.error('IP查询失败:', err)
if (err.name === 'AbortError') {
error.value = '查询超时,请检查网络连接后重试'
} else {
error.value = err.message || '网络错误,请稍后重试'
}
ipInfo.value = null
} finally {
loading.value = false
}
}
const copyIp = async () => {
const ip = ipInfo.value?.query || ipInfo.value?.ip || ''
if (!ip) return
try {
await navigator.clipboard.writeText(ip)
ElMessage.success('IP已复制到剪贴板')
} catch (e) {
const textArea = document.createElement('textarea')
textArea.value = ip
document.body.appendChild(textArea)
textArea.select()
document.execCommand('copy')
document.body.removeChild(textArea)
ElMessage.success('IP已复制到剪贴板')
}
}
const goBack = () => {
router.push('/developer')
}
onMounted(() => {
queryIp()
})2.3 效果截图
暂未生成该工具的效果截图。