我使用Vue框架,我有一个.vue文件,我希望在其中获取当前创建的Country()。我的代码如下:
<template>
<div id="show-blogs">
<h1>All Blog Articles</h1>
<input type="text" v-model="search" placeholder="search blogs" />
<!-- INPUT -->
<input type="text" v-model="message" required id="selectedCountry"/>
<!-- BUTTON ADD BLOG -->
<button v-on:click="selectCountry">Select country</button>
<div v-for="blog in filteredBlogs" class="single-blog">
<!-- router-link = href -->
<router-link v-bind:to="'/blog/' + blog.id">
<h2>{{ blog.country }}</h2>
</router-link>
<p>{{ blog.city }}</p>
<p>{{ blog.category }}</p>
<p>{{ blog.phoneNumber }}</p>
</div>
</div>
</template>
<script>
var currentCountry = getCurrentCountry();
import searchMixin from '../mixins/searchMixin';
export default {
data() {
return {
blogs: [],
search: '',
}
},
methods: {
selectCountry: function() {
selectedCountry = document.getElementById("selectedCountry").value;
this.$http.get('https://aggelies-7fde2.firebaseio.com/posts/' + selectedCountry + '.json').then(function(data) {
return data.json()
}).then(function(data) {
var blogsArray = [];
for (let key in data) {
data[key].id = key;
blogsArray.push(data[key]);
}
this.blogs = blogsArray;
});
},
getCurrentCountry: function() {
var currCountry;
var requestUrl = "http://ip-api.com/json";
$.ajax({
url: requestUrl,
type: 'GET',
async: false,
success: function(json) {
currCountry = json.country.toUpperCase();
},
error: function(err) {
}
});
alert(currCountry);
return currCountry;
}
},
created() {
this.$http.get('https://aggelies-7fde2.firebaseio.com/posts/' + currentCountry + '.json').then(function(data) {
return data.json()
}).then(function(data) {
var blogsArray = [];
for (let key in data) {
data[key].id = key;
blogsArray.push(data[key]);
}
this.blogs = blogsArray;
//console.log(this.blogs);
});
},
mixins: [searchMixin]
}
</script>
<style scoped>
.....
</style>
ajax代码工作正常,我得到了当前的国家/地区。但是当我在脚本getCurrentCountry()的开头调用时,该函数不起作用,我没有得到返回值,以便将它分配给currentCountry。有什么建议是错的吗?