I'm so confused how I should submit and handle edit forms in vuejs.
How I'm doing it now is I have a component called TreeForm.vue:
<template>
<div>
<v-text-field v-model="cloned_tree.root" />
<v-text-field v-model="cloned_tree.root" />
<v-file-input type="number" v-model="cloned_tree.fruits" />
<v-btn @click="$emit('save', {idx: tree_idx, tree: cloned_tree})">Save</v-btn>
</div>
</template>
<script>
export default {
props: {tree_idx: Number},
data() {
return {
cloned_tree: JSON.parse(JSON.stringify(this.$store.state.trees[this.tree_idx])),
};
},
};
</script>
And in the parent component I do:
<template>
<div>
...
<TreeForm tree_idx="0" @save="submitTreeForm" />
...
</div>
</template>
<script>
import {mapActions} from 'vuex';
export default {
methods: {
...mapActions(['submitTreeForm']),
},
};
</script>
And in my vuex I do:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.mydomain.com/api',
timeout: 10000,
withCredentials: true,
});
Vue.use(Vuex);
export default new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: {
trees: [
{
root: 'hello',
imageFile: require('some/picture'),
fruits: 5,
},
],
},
mutations: {
updateTree(state, payload) {
state.trees[payload.idx] = payload.tree;
},
},
actions: {
submitVideoForm({commit}, payload) {
api
.post('/trees/update/', payload)
.then(response => {
if (response.data.success == 1) {
commit('updateTree', payload);
} else {
console.log(response.data.success);
}
})
.catch(function(error) {
console.log(error);
});
},
},
});
But I feel like This is not the correct way to do it specially because I'm not using <v-form>
or <form>
tags. I also haven't incorporated validation yet, I'm thinking of using vuelidate. So please give me the best practice for submitting and handling edit form while validation is done by vuelidate.
Basically, the form
tag is not mandatory. Unless using some kind of CSS framework, the UI will look the same with or without the form
tag. But, it still has some pros:
Ben Nadel put it best in his blog post:
... it seems that using a FORM tag does have some benefits, depending on your particular situation:
- You need it if you want to execute a traditional (ie. non-AJAX) form post.
- You need it you want to capture the "submit" event programmatically.
- You need it in order for mobile Safari to show the "Go" button on the keyboard.
- You need it if you want to programmatically "reset" a form (ie. call reset()).
- It makes generic form serialization easier (since it groups input fields).
- You need it if you want to post files without the modern file API.
- You need it if you have to segregate fields with the same name.
Vue.js gets you covered in almost all these situations. But if it doesn't - use form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With