我在为Axios做合成曲。我想在execute()之后分配加载值。但是我不能分配
我想在axios可组合文件中控制加载值。如何分配 prop 的价值?
我尝试了const {error,loading:} = input. println();不管用...
<template>
<form class="ma-5">
<h2 class="ma-2">Sign-up</h2>
<v-text-field
v-model="state.username"
:error-messages="v$.username.$errors.map(e => e.$message)"
:counter="10"
label="Name"
required
@input="v$.username.$touch"
@blur="v$.username.$touch"
></v-text-field>
<v-text-field
v-model="state.email"
:error-messages="v$.email.$errors.map(e => e.$message)"
label="E-mail"
required
@input="v$.email.$touch"
@blur="v$.email.$touch"
></v-text-field>
<v-text-field
v-model="state.password"
:error-messages="v$.password.$errors.map(e => e.$message)"
label="password"
required
:type="show ? 'text' : 'password'"
@input="v$.password.$touch"
@blur="v$.password.$touch"
:append-icon="show ? 'mdi-eye' : 'mdi-eye-off'"
@click:append="show = !show"
></v-text-field>
<v-row justify="end">
<v-btn @click="signup">
submit
</v-btn>
</v-row>
<LoadingAlert :loading="loading"/>
</form>
</template>
<script>
const { error, loading, execute } = useAxios(
'v1/sign-up',
{
method: 'post',
},
{
immediate: false,
onSuccess: () => {
console.log("성공");
},
onError: err => {
console.log(error);
console.log(err);
}
},
);
</script>
这是axios.js文件
axios.defaults.baseURL = import.meta.env.VITE_APP_API_URL;
const defaultConfig = {
method: 'get',
};
const defaultOptions = {
immediate: true,
};
export const useAxios = (url, config = {}, options = {}) => {
const response = ref(null);
const data = ref(null);
const error = ref(null);
const loading = ref(false);
const { onSuccess, onError, immediate } = {
...defaultOptions,
...options,
};
const execute = body => {
data.value = null;
error.value = null;
loading.value = true;
axios(unref(url), {
...defaultConfig,
...config,
data: typeof body === 'object' ? body : {},
})
.then(res => {
response.value = res;
data.value = res.data;
if (onSuccess) {
onSuccess(res);
}
})
.catch(err => {
error.value = err;
if (onError) {
onError(err);
}
})
.finally(() => {
loading.value = false;
});
};
if (immediate) execute();
return {
response,
data,
error,
loading,
execute,
};
};
这是LoadingAlert.vue
<template>
<v-row justify="center">
<v-progress-circular
v-if="loading"
color="primary"
indeterminate>
</v-progress-circular>
</v-row >
</template>
<script>
export default {
props: {
loading: Boolean,
}
}
</script>
1条答案
按热度按时间bnl4lu3b1#
您似乎试图在Vue SFC(单文件组件)的脚本标记中导入和使用Vue 3可组合函数,但这不是完成它的正确方法。在Vue 3中,setup()方法是应该使用可组合函数的地方。
以下是如何修改Vue SFC以正确使用useAxios composable:
请仔细检查useAxios的正确导入。组件的React状态由React函数定义,然后使用React函数将其转换为具有可更容易地在模板中使用的引用的普通对象。由于加载值是返回的React状态的分量,因此它可以直接在组件模板中用作state.loading。
请记住,setup函数应该返回您打算在模板中使用的任何方法或变量。希望这能帮上忙。