Skip to content

Instantly share code, notes, and snippets.

@jhillacre
Last active June 21, 2022 22:31
Show Gist options
  • Save jhillacre/3d009d17457ff30a9cac5f72c9b77f5c to your computer and use it in GitHub Desktop.
Save jhillacre/3d009d17457ff30a9cac5f72c9b77f5c to your computer and use it in GitHub Desktop.
<script setup>
import { reactive } from "vue";
const updateState = reactive({
formValues: {},
formErrors: [],
fieldErrors: {},
});
const getFakeId = (array) => {
let fakeId;
do {
fakeId = Math.floor(Math.random() * Number.MIN_SAFE_INTEGER);
} while (array.some((item) => item.id === fakeId));
return fakeId;
};
const removeSign = (sign) => {
const index = updateState.formValues.signs.indexOf(sign);
updateState.formValues.signs.splice(index, 1);
};
const addSign = () => {
updateState.formValues.signs.push({
id: getFakeId(updateState.formValues.signs),
});
};
const updateObject = async () => {
// some PUSH
// update formValues
};
const fetchObject = async () => {
// some GET
// fill formValues
// example:
updateState.formValues = {
id: 1,
name: "Some Sign List Name",
signs: [
{
id: 1,
name: "Some Sign Name",
some_value: "foo",
},
{
id: 2,
name: "Another Sign Name",
some_value: "bar",
},
],
};
};
fetchObject();
</script>
<template>
<form-kit
type="form"
:actions="false"
v-model="updateState.formValues"
:errors="updateState.formErrors"
:input-errors="updateState.fieldErrors"
@submit="updateObject"
>
<form-kit type="hidden" name="id"/>
<form-kit type="text" name="name" label="Sign List Name" validation="required|length:0,255"/>
<h2>Signs</h2>
<form-kit type="list" name="signs">
<template #default="{ value: listValue }">
<form-kit type="group" v-for="sign of listValue" :key="sign.id">
<template #default="{ value: groupValue }">
<form-kit type="hidden" name="id"/>
<form-kit type="text" name="name"/>
<form-kit type="text" name="some_value"/>
<form-kit type="button"
@click="() => removeSign(groupValue)"
>
Remove
</form-kit>
</template>
</form-kit>
</template>
</form-kit>
<form-kit type="button" @click="addSign">
Add sign
</form-kit>
<form-kit type="submit">
Submit
</form-kit>
</form-kit>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment