繁体   English   中英

如何在 vue 3 中不触发 @update:modelValue 的情况下将 ref 设置为 ajax 调用的值?

[英]How can I set a ref to the value of an ajax call without triggering @update:modelValue in vue 3?

我有一个复选框,单击该复选框会使用模板中的@update:modelValue语法触发 ajax 调用。 但是,每当此页面加载时,都会调用 ajax 调用。

发生这种情况是因为当setup() function 运行时,我设置了isPushNotificationChecked ref,然后我在 onMounted function 中将其更新为不同 Z2705A83A5A0659EDACE3473458 调用的响应。

这是代码:

<template>
  <ion-checkbox
    slot="start"
    v-model="isPushNotificationChecked"
    @update:modelValue="updatePushNotifications"
  ></ion-checkbox>
</template>

<script>
import {
  IonCheckbox,
} from "@ionic/vue";
import { defineComponent, ref, onMounted } from "vue";
import axios from "axios";
import useToast from "@/services/toast";

export default defineComponent({
  name: "Settings",
  components: {
    IonCheckbox,
  },
  setup() {
    const isPushNotificationChecked = ref(false);

    onMounted(async () => {
      const response = await axios.get("settings");
      // Since I change the value here @update:modelValue in template triggers updatePushNotifications
      isPushNotificationChecked.value = response.data.notifications_enabled;
    });

    // This gets triggered on page load when it shouldn't
    const updatePushNotifications = async () => {
      if (isPushNotificationChecked.value) {
        axios.post("notifications/enable");
      } else {
        axios.post("notifications/disable");
      }

      useToast().success("Push notifications updated");
    };

    return {
      isPushNotificationChecked,
      updatePushNotifications,
    };
  },
});
</script>

如何在不删除单击复选框并触发 ajax 调用的行为的情况下将 ref 值设置为 ajax 调用的响应?

我的解决方案是改用在onMounted() function 中初始化的观察程序并删除@update:modelValue="updatePushNotifications"

<template>
  <ion-checkbox
    slot="start"
    v-model="isPushNotificationChecked"
  ></ion-checkbox>
</template>

<script>
import {
  IonCheckbox,
} from "@ionic/vue";
import { defineComponent, ref, onMounted } from "vue";
import axios from "axios";
import useToast from "@/services/toast";

export default defineComponent({
  name: "Settings",
  components: {
    IonCheckbox,
  },
  setup() {
    const isPushNotificationChecked = ref(false);

    onMounted(async () => {
      const response = await axios.get("settings");
      isPushNotificationChecked.value = response.data.notifications_enabled;

      // Watcher setup after ajax call.
      watch(isPushNotificationChecked, (value) => {
        if (value) {
          axios.post("notifications/enable");
        } else {
          axios.post("notifications/disable");
        }

        useToast().success("Push notifications updated");
      });
    });

    return {
      isPushNotificationChecked
    };
  },
});
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM