【发布时间】:2021-07-03 18:09:47
【问题描述】:
我有一个复选框,单击该复选框会触发使用模板中的@update:modelValue 语法的ajax 调用。但是,每当此页面加载时,都会调用 ajax 调用。
发生这种情况是因为当 setup() 函数运行时,我设置了 isPushNotificationChecked 引用,然后我在 onMounted 函数中将其更新为不同 ajax 调用的响应。
代码如下:
<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 调用的响应?
【问题讨论】:
标签: javascript vuejs3 vue-composition-api