vue 获取公网IP和地理位置
1. 引入脚本
在public
文件夹下面的index.html
中的body
标签里加入
<script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>111</title>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
</body>
</html>
2. 配置.eslintrc.js
在.eslintrc.js
中添加以下代码以解决returnCitySN未定义问题
globals:{
'returnCitySN': true
}
3. 直接使用
console.log(returnCitySN)
// {"cip": "21.69.11.119", "cid": "000000", "cname": "北京市"}
const ip = returnCitySN['cip'] || '0.0.0.0'
const city = returnCitySN['cname'] || '未知'
4. 保存后使用
- 在
App.vue
的created()
方法中将ip信息保存到sessionStorage
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
created() {
sessionStorage.setItem('ip', returnCitySN['cip'] || '0.0.0.0')
sessionStorage.setItem('city', returnCitySN['cname'] || '未知')
}
}
</script>
- 在需要的地方,直接获取
const ip = sessionStorage.getItem('ip')
const city = sessionStorage.getItem('city')