Forms
In this chapter we create a form which inserts a new user into the Vuex store. This chapter assumes that you've completed the previous chapter on how to manage application state.
Getting Started
Create a new component file or open an existing one (e.g. ./src/app/components/app.vue
), then set the code as shown below.
<template>
<div>
<!-- Form -->
<form novalidate v-on:submit.prevent="adduser">
<input type="text" v-model="user.name" placeholder="User name"/>
<input type="checkbox"v-model="user.enabled"/> Enabled
<button>+ Add User</button>
</form>
<!-- List -->
<pre v-for="user in users">{{user}}</pre>
</div>
</template>
<script>
export default {
data: () => ({
user: {
name: '',
enabled: true
}
}),
computed: {
users () {
return this.$store.state.users.reverse();
}
},
methods: {
adduser () {
return this.$store.commit('addUser', JSON.parse(JSON.stringify(this.user)));
}
}
}
</script>
Dynamic Inputs
Here we add a tags
field to the user, to show how easy we can create dynamic form fields.
Let's make some adjustments in the code example above.
<template>
<div>
<!-- Form -->
<form ...>
...
<template v-for="tag in user.tags">
<input type="text" v-model="tag.name" placeholder="User tag"/>
</template>
<button v-on:click.prevent="newTag">+ New Tag</button>
...
</form>
</div>
</template>
<script>
export default {
data () {
return {
user: {
...
tags: [{name: ''}]
}
};
},
methods: {
...
newTag () {
this.user.tags.push({name: ''});
}
}
};
</script>
Validation
The simplest and the most convenient way for validating a form is to use the RawModel.js framework. Use vue-rawmodel plugin to implement this into your Vue application.