我的应用有一个功能,用户可以根据“血型”和“城市”以及地区过滤结果。将使用 Axios for Vuejs 通过“URL”查询字符串从数据库检索结果。示例网址为: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
}
}
最佳答案
您可以尝试下面的代码。
创建一个新对象(称为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
}
})
关于javascript - 确定pr消除空键:value from an object for multiple filtering purposes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455003/