Next we add event handling and dynamic content to our EventRegistration.vue component.
-
Create another file registration.js in the same folder which will contain the Javascript code for the EventRegistration.vue component.
-
Create constructor methods:
function PersonDto (name) { this.name = name this.events = [] } function EventDto (name, date, start, end) { this.name = name this.eventDate = date this.startTime = start this.endTime = end }
-
Add data variables to the export declaration of the component.
export default { name: 'eventregistration', data () { return { people: [], newPerson: '', errorPerson: '', response: [] } }, //... }
-
Add an initialization function below the data part.
created: function () { // Test data const p1 = new PersonDto('John') const p2 = new PersonDto('Jill') // Sample initial content this.people = [p1, p2] },
-
Add event handling method createPerson():
methods: { createPerson: function (personName) { // Create a new person and add it to the list of people var p = new PersonDto(personName) this.people.push(p) // Reset the name field for new people this.newPerson = '' } }
-
Open
EventRegistration.vue
and link the Javascript file as script:<script src="./registration.js"> </script>
-
Change the static template content for the person list to dynamic bindings:
-
We iterate along all people in data property
people
and dynamically print their name by{{ person.name }}
(see list rendering) -
We print the (currently empty) list of events to which a person is registered to.
<table> <tr v-for="person in people" > <td>{{ person.name }}</td> <td> <ul> <li v-for="event in person.events"> {{event.name}} </li> </ul> </td> </tr> <!-- ... --> </table>
-
-
Link input field content with data variable
newPerson
and button clicks for Create Person for event handler methodcreatePerson()
.<table> <!-- ... --> <tr> <td> <input type="text" v-model="newPerson" placeholder="Person Name"> </td> <td> <button @click="createPerson(newPerson)">Create Person</button> </td> </tr> </table>
-
Bind the error message to the corresponding variable
errorPerson
by extending the<span>
tag with conditional rendering.-
The error message will only appear if the data property
errorPerson
is not empty. -
You may wish to further refine error handling in case of empty string content for
newPerson
by adding&& !newPerson
to the condition.<span v-if="errorPerson" style="color:red">Error: {{errorPerson}} </span>
-
-
Run your frontend application and observe that two people are listed.