tdata
Version:
Fetch your data, send your form easily. for vue 3.
192 lines (177 loc) • 3.67 kB
JavaScript
import { h } from 'vue';
import axios from 'axios';
import { h as h$1 } from '@vue/runtime-core';
var TFetch$1 = {
name: "TFetch",
props: {
url: {
type: String,
required: true,
},
method: {
type: String,
default: "get",
},
options: {
type: Object,
default: () => ({}),
},
baseURL: {
type: String,
required: false,
},
axios: {
type: [Function, Object],
required: false,
},
},
data: () => ({
json: [],
loading: false,
response: {},
error: null,
errorMessage: "",
}),
async created() {
this.loading = true;
let axiosInstance = null;
if (this.axios) {
axiosInstance = this.axios;
} else {
axiosInstance = axios.create({ baseURL: this.baseURL });
}
axiosInstance[this.method](this.url, this.options)
.then((res) => {
this.response = res;
this.json = res.data;
})
.catch((error) => {
this.error = error;
this.response = error.response;
this.errorMessage = error.message;
})
.finally(() => {
this.loading = false;
});
},
render() {
return (
this.$slots.default &&
this.$slots.default({
json: this.json,
loading: this.loading,
response: this.response,
error: this.error,
errorMessage: this.errorMessage,
})
);
},
};
const TFetchHOC = (options) => ({
render() {
return h(
TFetch$1,
{ ...options },
{
default: (props) => this.$slots.default(props),
}
);
},
});
var TForm$1 = {
name: "TForm",
props: {
url: {
type: String,
required: true,
},
method: {
type: String,
default: "post",
},
form: {
type: Object,
default: () => ({}),
},
options: {
type: Object,
default: () => ({}),
},
baseURL: {
type: String,
required: false,
},
axios: {
type: [Function, Object],
required: false,
},
},
data: () => ({
json: [],
loading: false,
response: {},
error: null,
errorMessage: "",
}),
render() {
const handleSubmit = async () => {
this.loading = true;
let axiosInstance = null;
if (this.axios) {
axiosInstance = this.axios;
} else {
axiosInstance = axios.create({ baseURL: this.baseURL });
}
axiosInstance[this.method](this.url, this.form, this.options)
.then((res) => {
this.response = res;
this.json = res.data;
})
.catch((error) => {
this.error = error;
this.response = error.response;
this.errorMessage = error.message;
})
.finally(() => {
this.loading = false;
});
};
return h$1(
"form",
{
onSubmit: (event) => {
event.preventDefault();
handleSubmit();
},
},
this.$slots.default({
json: this.json,
loading: this.loading,
response: this.response,
error: this.error,
errorMessage: this.errorMessage,
})
);
},
};
const TFormHOC = (options) => ({
render() {
return h(
TForm$1,
{ ...options },
{
default: (props) => this.$slots.default(props),
}
);
},
});
const TFetch = TFetchHOC;
const TForm = TFormHOC;
var index = {
install: (app, options) => {
app.component("TFetch", TFetchHOC(options));
app.component("TForm", TFormHOC(options));
},
};
export default index;
export { TFetch, TForm };