我有一个包含邮政编码的输入字段。在提交时,我想将邮政编码作为对象传递给 axios 请求。我在这里创建了一个 CodeSandbox:https ://codesandbox.io/s/determined-beaver-8ebqc
相关代码为:
应用程序.vue
<template>
<div id="app">
<input v-model="postcode" type="text" placeholder="Enter Postcode">
<button @click="getAddress">Submit</button>
</div>
</template>
<script>
import useAxios from "@/composition/use-axios";
export default {
name: "App",
setup() {
const { sentData, response, fetchData } = useAxios(
"api/address/lookup-address",
"postcode",
"Failed Finding Address"
);
return {
postcode: sentData,
address: response,
getAddress: fetchData
};
}
};
</script>
使用-axios.js
import { reactive, toRefs } from "@vue/composition-api";
import axios from "axios";
export default function (url, objectData, errorMessage) {
const state = reactive({
sentData: null,
response: null
});
const fetchData = async () => {
console.log("Sent Data:", state.sentData);
console.log("Response:", state.response);
console.log("URL:", url);
console.log("Object Data:", objectData);
console.log("Object:", { [objectData]: state.sentData });
console.log("Error Message:", errorMessage);
const config = { headers: { "Content-Type": "application/json" } };
try {
const res = await axios.post(url, [objectData]: state.sentData, config);
state.response = await res.data;
} catch (error) {
// Error handling stuff
}
}
return { ...toRefs(state), fetchData };
}
以这种方式将邮政编码输入字符串转换为对象似乎很 hacky。此外,如果我需要向 axios 请求发送多个参数,这会变得非常混乱。说如果我想通过{ id: "1234", user: "Me" }
,我希望能够像这样构建:
sentData = { id: ${id}, user: ${user} }
但我无法做到这一点。这样做的正确方法是什么,以便我可以保持 use-axios 通用?