Use object properties as parameters to GET request - javascript

Right now I have this two components:
pesquisar.vue
form.mb-3(#submit.prevent="getPessoaFisica(object)")
Search(:object='object')
button.btn.btn-sm.btn-success.d-none(type="submit")
.fa.fa-search
...
data() {
return {
object: {
Cd_Pessoa: null,
Nm_Pessoa: null,
Nm_Apelido: null,
Nr_Documento: null,
Nm_Officer: null,
Tp_Registro: null,
Cd_TipoID: null,
},
page: undefined,
list: undefined,
};
},
methods: {
getPessoaFisica(obj, page = 1, count = 18) {
this.$axios
.get("/pessoaFisica", {
params: {
obj,
page,
count
}
})
.then(res => {
this.list = res.data;
});
}
},
search.vue
<template lang="pug">
.row(#input="$emit('input', object)")
.col-md-4.mb-1(v-for='property in Object.keys(object)')
.row
.col-auto.pr-0 {{property}}:
.col
input.form-control.form-control-sm.py-0(v-model='object[property]')
</template>
<script>
export default {
props: ['object']
}
</script>
I'm using the object object in pesquisar.vue to dynamically create inputs in my view.
When I submit the form with random data, I'm getting this request:
http://localhost/abc?obj=%7B%22Cd_Pessoa%22:null,%22Nm_Pessoa%22:%22her%22,%22Nm_Apelido%22:null,%22Nr_Documento%22:null,%22Nm_Officer%22:null,%22Tp_Registro%22:null,%22Cd_TipoID%22:null%7D&page=1&count=18
What I really wanted was this:
http://localhost/abc?Nm_Pessoa:"her"&page=1&count=18
Basically what I wanted was to use the object properties as parameters to GET request.
Any help, please?

Try spreading the object properties using the object spread operator ...obj:
// ...
this.$axios
.get("/pessoaFisica", {
params: {
...obj,
page,
count
}
})
.then(res => {
this.list = res.data;
});

Related

How do I properly get the state data set with nuxtServerInit in Nuxt

I have a situation where I get data from api in nuxtServerInit and write it to the store's state variable like so
let categoriesService = new Categories(this.$axios);
categoriesService.current().then((resp) => {
if (resp.data.success) {
const navCategoryRoutes = resp.data.items
.filter((item) => {
return item.label !== "" && item.label;
})
.map((item) => {
item.label = item.label.toLowerCase();
item.isSelected = false;
item.url = "/category/" + item.name + "/";
return item;
});
commit("nav/setNavCategoryRoutes", navCategoryRoutes);
}
});
I log it in the setter to the console and I can see that below the assignment declaration and I can see it's there
state: {
categoryRoutes: [
[Object],
[Object],
[Object],
[Object],
[Object]
]
},
In the getter, however, it's always an empty array ;/
export const getters = {
getNavCategoryRoutes(state) {
console.log({ getter: state });
return state.categoryRoutes;
},
};
getter: {
categoryRoutes: []
}
and in the file where I try to use it obviously it is empty as well
categories() {
console.log({
header: this.$store.getters["nav/getNavCategoryRoutes"],
});
return this.$store.getters["nav/getNavCategoryRoutes"];
},
I have tried to fetch it in computed property:
computed: {
categories() {
return this.$store.getters["nav/getNavCategorysRoutes"];
},
},
and in the mounted lifecycle method:
mounted() {
this.categories = this.$store.getters["nav/getNavCategoryRoutes"];
},
But the problem is earlier in the getter I think, I just don't know what am I doing wrong ;/ this getter is no different from the working ones. Would you please point me in the proper direction, I am out of ideas about what to do with that, thanks a lot.
To get data in nuxtServerInit, add nuxtServerInit to actions:
nuxtServerInit({ commit }) {
// get data then commit mutation
})

Use props with forEach in vuejs

I'm desperately trying to use my props 'datas' with a foreach.
When I put my data in a "test" data, it works.
Example :
data() {
return {
postForm: this.$vform({}),
test: [{"name":"Couleur yeux","id":3,"answer":null},{"name":"Hanches","id":6,"answer":"'Test'"}],
}
},
computed: {
},
methods: {
createForm() {
this.test.forEach((data) => {
if (data.answer) {
this.$set(this.postForm, data.id, data.answer)
}
})
}
},
But if I use my props directly, it doesn't work. I have a message "this.datas.forEach is not a function".
But my props has exactly the same data and the same structure as my "test" data.
Don't work:
this.datas.forEach((data) => {
if (data.answer) {
this.$set(this.postForm, data.id, data.answer)
}
})
I also tried to transform my props into data() but it doesn't work
data() {
return {
postForm: this.$vform({}),
test: this.datas
},
"this.datas.forEach is not a function"
This mean that datas is not an Array instance because forEach is method from array prototype.
Right now, this.datas does not exist. You never give this the state with the key datas.
It looks like you're trying to go through this.test, which is an array of objects. Is that right?
If that's the goal, you can do so:
data() {
return {
postForm: this.$vform({}),
test: [{"name":"Couleur yeux","id":3,"answer":null},{"name":"Hanches","id":6,"answer":"'Test'"}],
}
},
methods: {
createForm() {
let arrayOfAnswers = []
this.test.forEach((data) => {
if (data.answer) {
arrayOfAnswes.push(data.answer)
}
})
this.arrayOfanswers = arrayOfAnswers
}
},

vue escaping object child as parameter

I want to build a helper function to reduce my redundant code lines.
Instead of doing nearly the same over and over i want to use that function to simple add a parameter and reduce the lines of code.
<template>
<div>
<!-- TODO: ADD ALL PROPS NOW! -->
<UserInfo
:user-name="userData.userName"
:budget="userData.budget"
:leftover="userData.leftover"
/>
<UserIncExp />
</div>
</template>
<script>
import UserInfo from '../User/UserInfo.vue';
import UserIncExp from '../User/UserIncExp/_UserIncExp.vue';
export default {
components: {
UserInfo,
UserIncExp
},
data() {
return {
test: '',
userData: {
userName: '',
budget: '',
leftover: '',
inc: [],
exp: [],
active: false
}
};
},
computed: {},
watch: {
'$route.params.userId': {
handler() {
this.loadUserDataFromState();
}
},
immediate: true
},
created() {
this.loadUserDataFromState();
},
methods: {
loadUserDataFromState() {
// this.userData.userName = this.$store.state.users[this.$attrs.userId].userName;
// this.userData.budget = this.$store.state.users[this.$attrs.userId].salery;
// this.userData.leftover = this.$store.state.users[this.$attrs.userId].leftover;
this.helper(userName);
},
// CHECK HERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
helper(data) {
return this.userData.data = this.$store.state.users[this.$attrs.userId].data;
}
}
};
</script>
<style>
</style>
but i dont get why i am not able to use data as an parameter to use it then in the executed function
Use bracket notation like so:
loadUserDataFromState() {
this.helper("userName");
},
helper(key) {
this.userData[key] = this.$store.state.users[this.$attrs.userId][key];
}
helper expects a key (which is a string).
Note: helper doesn't need to return anything.
An alternative way which doesn't require the function helper at all is to use a loop over an array of keys like so:
loadUserDataFromState() {
for(let key of ["userName", "salery", "leftover"]) {
this.userData[key] = this.$store.state.users[this.$attrs.userId][key];
}
}
it just loops over the keys in the array ["userName", "salery", "leftover"] and dynamically copy the values from the source object to this.userData.

Convert api response array to another array to pass to Vue prop

I want to use this vue flipbook component and it needs a array of image urls for the prop "pages". My posts response is coming from the wordpress rest api.
I need to get the "image" property from the response array and convert it into another array of image urls. Normally I would use the posts() in computed like v-for=post in posts in my template and display the image like post.image_full in the loop..
Flipbook component:
<Flipbook
class="flipbook"
:pages="imagesArray" <--- images array here
v-slot="flipbook"
ref="flipbook"
>
</Flipbook>
My Posts.vue component:
export default {
name: 'GridOne',
props: {
page: {
type: Number,
required: true
}
},
data() {
return {
request: {
type: 'posts',
params: {
per_page: this.$store.state.site.posts_per_page,
page: this.page
},
showLoading: true
},
totalPages: 0
}
},
computed: {
posts() {
return this.$store.getters.requestedItems(this.request) <--- my response array
}
},
methods: {
getPosts() {
return this.$store.dispatch('getItems', this.request)
},
setTotalPages() {
this.totalPages = this.$store.getters.totalPages(this.request)
}
},
created() {
this.getPosts().then(() => this.setTotalPages())
}
}
You can use JavaScript "map" function. This function takes one array and return a new one.
// If this is the response array....
const response = [{name: 'image 1', url: 'https://uri.com/img1'}, ...]
// Then you return something like this
response.map(item => {
return {
...item,
image_full: item.url
}
})

Determining pr eliminating empty key:value from an object for multiple filtering purposes

My app has a feature where users can filter results based on "blood group" and "city", and areas. Results will be retrieved from DB using Axios for Vuejs through "URL" query strings. Example url is: http://example.com/api/results?blood=a+&city=london
It should work in a way that when a user select just blood group from select menu: the url would exclude the city parameter. But from my current code, I can't get it stripped of, as a result, the database query returns no results on the basis that cityreturns null value.
Here's what I have in my Vue component:
<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>
My query is how can I remove or check if any of the following properties contains empty value, so that I do not include them in axios params?
let request = {
params: {
blood: this.requestedBlood,
city: this.requestedCity,
dist: this.requestedDist,
area: this.requestedArea
}
}
You can try below code.
Create a new object(called testParams) and add that object in params.suppose requestedCity is selected(not only but any variable is selected ). Then you can do like below.
if(requestedCity.length!=0)
{
testParams["city"]=requestedCity; // OTHERWISE DON'T ADD IN testParams object
}
Finally while making request through axios add testParams in params object like below.
axios.get('/yourUrl/',{
params:{
testParams //here vue will automatically sets 'testParams':testParams
}
})
I got it working with the following approach:
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
})

Categories