我正在嘗試根據 API 回應設定復選框的狀態,但我無法更改其狀態。
應用程式.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" @submit.prevent>
<h3 >{{ options.general.section_label }}</h3>
<div >
<el-switch
v-model="enableQuickView"
size="large"
inline-prompt
:active-icon="Check"
:inactive-icon="Close"
/>
</div>
</form>
</template>
API 回應:
{
"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"
}
}
}
}
}
}
如果您查看我正在使用的 App.vue 模板{{ options.general.section_label }},它運行良好。這是一個章節標題,我不需要任何反應狀態。
但是,對于像我這樣的元素,checkbox & select我希望它們具有反應性,以便稍后我可以觀察用戶更改的狀態并稍后將其更新到 API。
謝謝
uj5u.com熱心網友回復:
嘗試將您的值轉換為布林值:
...
state.options = res.data.settings;
state.enableQuickView =
state.options.general.section_fields.enable_quick_view.value === 'true'
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/484197.html
標籤:Vue.js Vuejs3 vue-composition-api Vue 反应性
