如何根据 Vue js 3 中的 API 响应替换反应值

How to replace reactive value based on API response in Vue js 3

我正在尝试根据 API 响应设置复选框的状态,但我无法更改其状态。

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 回复:

{
    "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"
                    }
                }
            }
        }
    }
}

如果您查看我正在使用 {{ options.general.section_label }} 的 App.vue 模板,它运行良好。这是一个章节标题,我不需要任何反应状态。

但是,对于像 checkbox & select 这样的元素,我希望它们是反应式的,以便稍后我可以观察用户更改的状态并稍后将其更新为 API。

谢谢

尝试将您的值转换为布尔值:

...
state.options = res.data.settings;
state.enableQuickView = 
  state.options.general.section_fields.enable_quick_view.value === 'true'
...