Reputation: 157
I am trying to set the state of the checkbox based on the API response but I am not able to change its state.
App.vue
<script setup>
import { ref, toRefs, reactive, onMounted } from "vue";
import axios from "axios";
import { Check, Close } from "@element-plus/icons-vue";
import Loading from "../Loading.vue";
let state = reactive({
options: {},
errors: [],
loading: true,
enableQuickView: true, // 👈🏻 How to replace this value based on the API response?
});
let { loading, options, enableQuickView } = toRefs(state);
let BASE_API_URL = 'http://wpvue.local/wp-json/quick_view_api/get_settings/';
// 👇 Doing API call to get the settings.
let FetchOptions = () => {
axios
.get(BASE_API_URL + "get_options")
.then((res) => {
state.options = res.data.settings;
console.log(res.data.settings);
state.loading = false;
})
.catch((err) => {
console.log(err);
state.errors = err;
});
};
// 👇 Invoke FetchOptions function.
onMounted(() => {
FetchOptions();
});
</script>
<template>
<Loading v-if="loading" />
<form v-else id="xox-settings-form" class="xox-form" @submit.prevent>
<h3 class="option-box-title">{{ options.general.section_label }}</h3>
<div class="input">
<el-switch
v-model="enableQuickView"
class="enable-addonify-quick-view"
size="large"
inline-prompt
:active-icon="Check"
:inactive-icon="Close"
/>
</div>
</form>
</template>
API response:
{
"settings": {
"general": {
"section_label": "General",
"section_fields": {
"enable_quick_view": {
"label": "Enable Quick View",
"description": "",
"type": "checkbox",
"value": "true"
},
"quick_view_btn_position": {
"label": "Quick View Button Position",
"description": "",
"type": "select",
"value": "",
"choices": {
"after_add_to_cart_button": "After Add to Cart Button",
"before_add_to_cart_button": "Before Add to Cart Button"
}
}
}
}
}
}
If you look at the App.vue template I am using {{ options.general.section_label }}
& it is working perfectly. This was a section title & I don't need any reactive state on that.
But, for elements like checkbox & select
I want them to be reactive so that later I can watch the state changed by user & update it to the API later.
Thank you
Upvotes: 4
Views: 1522
Reputation: 23510
Try to convert your value to boolean:
...
state.options = res.data.settings;
state.enableQuickView =
state.options.general.section_fields.enable_quick_view.value === 'true'
...
Upvotes: 1