如何在Vue中使用composition api正确将输入值传递给函数?

时间:2020-08-30 14:04:50

标签: vue-composition-api

我有一个包含邮政编码的输入字段。在提交时,我想将邮政编码作为对象传递给axios请求。我在这里创建了一个CodeSandbox:https://codesandbox.io/s/determined-beaver-8ebqc

相关代码为:

App.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>

use-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 };
}

以这种方式将邮政编码输入字符串转换为对象似乎很麻烦。另外,如果我需要向axios请求发送多个参数,这将变得非常混乱。假设我想通过{ id: "1234", user: "Me" },那么我希望能够像这样构造

sentData = { id: ${id}, user: ${user} }

但是我无法做到这一点。这样做可以使我保持use-axios通用的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您将需要从composition-api导入ref,reactive和compute,然后像这样使用它们:

<script>
import useAxios from "@/composition/use-axios";
import { ref, reactive, computed } from "@vue/composition-api";

export default {
  name: "App",

  setup() {
    let object = ref("");
    let state = reactive({ postcode: "" });
    const sentDataObject = computed(() => {
      state.postcode = object;
      return state;
    });
    const addressList = useAxios(
      "api/address/lookup-address",
      sentDataObject.value,
      "Failed Finding Address"
    );

    return {
      addresses: addressList.response,
      postcode: object,
      getAddress: addressList.fetchData
    };
  }
};
</script>

在此处查看Codesandbox演示:https://codesandbox.io/s/dawn-glade-ewzb7