我的应用程序具有一项功能,用户可以根据其“血统”和“城市”以及区域来过滤结果。将通过“ URL”查询字符串使用Axios for Vuejs从数据库检索结果。网址示例为:http://example.com/api/results?blood=a+&city=london
它的工作方式应是当用户从选择菜单中仅选择血型时:URL将排除city
参数。但是从我当前的代码来看,我无法去除它,因此,数据库查询基于city
返回null
的值不返回任何结果。
这就是我的Vue组件中的内容:
<script>
export default {
props: ['user'],
data() {
return {
auth_user: this.user,
results: {},
blood_groups: "",
cities: "",
districts: "",
areas: "",
donorUrl: "/api/donors",
requestedBlood: "",
requestedCity: "",
requestedDist: "",
requestedArea: "",
params: {}
};
},
created() {
this.fetchDonors();
this.fetchCities();
},
methods: {
fetchDonors() {
let url = "/api/donors";
axios.get(url).then(response => {
this.results = response.data.data;
this.blood_groups = [...new Set(response.data.data.map(x=> x.blood_group))];
});
},
fetchCities() {
let url = "/api/location_type/cities";
axios.get(url).then(response => {
this.cities = response.data.cities
})
},
selected_blood_group(event) {
this.requestedBlood = event.target.value;
this.get();
},
get_city(event) {
this.requestedCity = event.target.value;
this.get();
},
get() {
let request = {
params: {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
}
axios.get('/api/donors', request).then(response => {
this.results = response.data.data
})
}
},
};
</script>
我的查询是如何删除或检查以下任何属性是否包含空值,以便不将它们包括在axios
参数中?
let request = {
params: {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
}
答案 0 :(得分:1)
您可以尝试以下代码。
创建一个新对象(称为 testParams ),然后将该对象添加到params中。假设选择了 requestedCity (不仅选择了任何变量)。然后,您可以像下面这样。
if(requestedCity.length!=0)
{
testParams["city"]=requestedCity; // OTHERWISE DON'T ADD IN testParams object
}
最后,通过axios发出请求时,在如下所示的params对象中添加testParams。
axios.get('/yourUrl/',{
params:{
testParams //here vue will automatically sets 'testParams':testParams
}
})
答案 1 :(得分:0)
我可以通过以下方法使用它:
let request = {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
for(let k in request)
if(!request[k]) delete request[k];
axios.get('/api/donors', {
params: request
}).then(response => {
this.results = response.data.data
})