Issue
I've got a checkbox with filtering, e.g.:
if false => display all data (one endpoint in API) if true => display only filtered data (another endpoint)
I struggle with sending different requests like this
<template>
<div>
<div style="display: flex;
justify-content: center;">
<div class="col-md-9">
<b-form-checkbox v-model="my__specialization"
value=true
unchecked-value=false
@change="filterOrdersSpec()"
>Show filtered</b-form-checkbox>
<p>{{ my__specialization }}</p>
</div>
</div>
<div v-for="el in APIData" :key="el.id" >
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Orders',
data () {
return {
APIData: [],
my__specialization: false,
}
},
methods: {
filterOrdersSpec() {
if (this.my__specialization) {
axios
.get('/api/v1/filter-orders/specs')
.then(response => {
this.APIData = response.data.results
})
}
else {
axios
.get('/api/v1/orders/get')
.then(response => {
this.APIData = response.data.results
})
}
},
},
created () {
axios
.get('/api/v1/orders/get')
.then(response => {
this.APIData = response.data.results
})
.catch(err => {
console.log(err)
})
},
}
</script>
This construction does filter Data on setting checkbox to TRUE, but when setting FALSE, the request to filter is sent again. The question is - why and how to fix it?
Solution
Root cause of the problem : this.my__specialization
returning boolean as a string "true"
/"false"
. Hence, if (this.my__specialization) { ... }
condition will always return true as it consider the value as string instead of boolean.
Solution : You have to convert the string value into a boolean.
if (this.my__specialization === "true") {
}
Live Demo :
new Vue({
el: '#app',
data() {
return {
APIData: null,
my__specialization: false
}
},
methods: {
filterOrdersSpec() {
this.APIData = (this.my__specialization === "true") ? 'Endpoint 1' : 'Endpoint 2';
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/>
<div id="app">
<b-form-checkbox
v-model="my__specialization"
value="true"
unchecked-value="false"
@input="filterOrdersSpec()"
>Show filtered</b-form-checkbox>
<div>my__specialization: <strong>{{ my__specialization }}</strong></div>
<div>APIData: <strong>{{ APIData }}</strong></div>
</div>
Answered By - Rohìt Jíndal Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.