Javascript 在VueJS中定义引用变量
我想获取用户IP地址并将其保存到数据库中,但无法引用它们。 这是我正在使用的脚本Javascript 在VueJS中定义引用变量,javascript,laravel,vue.js,Javascript,Laravel,Vue.js,我想获取用户IP地址并将其保存到数据库中,但无法引用它们。 这是我正在使用的脚本 <script> export default { data(){ return { } }, methods: { setRating(){ fetch('https://ipapi.co/json/') .t
<script>
export default {
data(){
return {
}
},
methods: {
setRating(){
fetch('https://ipapi.co/json/')
.then(function(response) {
return response.json();
})
.then(function(data) {
var ip = data.ip;
console.log(data.ip);
});
var pathArray = location.pathname.split('/');
var uid = pathArray[2];
fetch('/api/rating/new',{
method: 'post',
body: JSON.stringify({business:1, **user:3**, rating:this.rating}),
headers: {
'content-type': 'application/json'
}
}).then(res => res.json())
.then(data => {
swal.fire(
'The Business Rated!',
'Done.',
'success'
)
}).catch(err => {
swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Request Faild',
})
});
},
},
mounted() {
this.getRating();
console.log('Component mounted.');
}
}
</script>
这就是错误:
“ReferenceError:未定义IP”
当我将this.ip放入数据库时,它的响应为空。尝试使用
async/wait
重写代码,以正确访问变量ip
或在setRating
请求时定义var ip=null
,然后只为其赋值ip=data.ip代码>
我建议您使用第一种方式,因为它看起来更清晰、有序,并且易于阅读
body: JSON.stringify({business:1, **user:ip**, rating:this.rating}),