【问题标题】:How to set default value for a pair of buttons based on API response? VueJS如何根据 API 响应为一对按钮设置默认值? VueJS
【发布时间】:2023-02-10 15:07:18
【问题描述】:

我有一对按钮,必须根据我从 API 获得的响应进行切换。

我为此使用的代码

<div class="small-7 column btn-switch">
          <span class="switch-statement">"Is it mandatory"</span>
          <button
            :class="!isMandatory ? 'button--secondary' : 'button--tertiary'"
            class="button button-border"
            @click="setMandatory(false)"
          >
           "No"
          </button>
          <button
            :class="isMandatory ? 'button--secondary' : 'button--tertiary'"
            class="button"
            role=`your text`"button"
            @click="setisMandatory(true)"
          >
            "Yes"
          </button>
        </div>

我尝试对按钮使用 v-if,但正如我所料,它没有用。有没有其他方法可以做到这一点?

【问题讨论】:

    标签: javascript vue.js frontend


    【解决方案1】:

    isMandatory 的值可能会根据您正在进行的 API 调用的响应而变化。首次加载页面时,它将是您为其提供的任何默认值,当 API 稍后返回响应时,页面不会被刷新。

    我需要有关代码结构的更多信息,但我目前的猜测是您需要将 isMandatory 转换为 ref

    例如,如果您的代码如下所示:

    <script setup>
      isMandatory = false;
    
      // -> some API call handling
      isMandatory = apiResponse
    </script>
    <template>
      ...
    </template>
    

    把它变成这样的东西:

    <script setup>
      isMandatory = ref(false);
    
      // -> some API call handling
      isMandatory.value = apiResponse
    </script>
    <template>
      ...
    </template>
    

    然后 template 将在 isMandatory 的值更改时响应地更改。

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2018-09-09
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      相关资源
      最近更新 更多