Making A Simple Component With Props & Validation In Vue.JS

Picture shows Jason A. Martin - Software Engineer, Indie Game Developer, Tech Evangelist, Entrepreneur.

This is a simple example on how to use components with Vue.JS.

I've created a component called "report" and used it for each item in the studentData array.

I also give an example on how to pass props (data) into a component, how to validate the data and how to have default data in case nothing is passed in.

Nothing too fancy here. This is a good getting-started task when diving into the Vue.JS world.

As usual, I'll show off the example and then provide the code below.

Also, if you want to mess around with Vue.JS quickly, I created a pen at CodePen that you can fork.

Vue.JS Template CodePen



Vue.component('report', {
  props: {
    name: {
      type: String,
      required: true,
      default: 'A Girl Has No Name'
    grade: {
      type: Number,
      required: false,
      default: 0
  template: `<div><h2>{{ name }}</h2><p>{{ name }}'s grade is: {{ grade }}</p></div>`

new Vue({
  el: '#app',
  data: {
    studentData: [
      { name: 'Jason Martin', grade: 100},
      { name: 'Cersei Lannister', grade: 88},
      { name: 'Daenerys Targaryen', grade: 94},
      { name: 'Joffrey Baratheon'},
      { name: 'Tyrion Lannister', grade: 87},
      { name: 'Arya Stark', grade: 96 },
      { name: 'Ramsay Bolton'}