Page
- A button to create new object
- Listing of existing object, and allow edit
<template> <div> <b-button @click="editBot({})">New</b-button> <div v-for="item in items" :key="item.name"> {{ item.name }} <b-button @click="editBot(item)">Edit</b-button> </div> <b-modal id="bot" title="Bot" @ok="saveBot"> <bot-form ref="botForm" :item="formItem" /> </b-modal> </div></template><script>import BotForm from '~/components/BotForm.vue'export default { data() { return { items: [ { id: 1, name: 'R2D2' }, { id: 2, name: 'WALL-E' } ], formItem: {} } }, methods: { editBot(item) { this.formItem = Object.assign({}, item) this.$bvModal.show('bot') }, async saveBot(bvModalEvent) { console.log('saveBot') bvModalEvent.preventDefault() const form = this.$refs.botForm if (form.validate()) { const data = await form.submit() if (data.id) { for (const item of this.items) { if (item.id == data.id) { item.name = data.name break } } } else { const nextId = Math.max.apply(Math, this.items.map((item) => { return item.id })) data.id = nextId + 1 this.items.push(data) } this.$nextTick(() => { console.log('close') this.$bvModal.hide('bot') }) } else { alert('Validate Error') } } }, components: { BotForm }}</script>
Form
Edit components/BotForm.vue
<template> <b-form ref="form" @submit="submit"> <b-form-group id="input-group-1" label="Name" label-for="input-1" > <b-form-input id="input-1" v-model="item.name" placeholder="" required ></b-form-input> </b-form-group> </b-form></template><script>export default { props: ['item'], methods: { validate() { const valid = this.$refs.form.checkValidity() console.log('valid', valid) return valid }, async submit() { // alert('submit') const r = await fetch('/test.json', { method: "GET", // method: "POST", // body: JSON.stringify(this.item) }) if (r.status == 200) { alert('Submit sucessful') return this.item } else alert('Submit failed') } }} </script>
Form Validation
For proper form validation, can consider