DEV Community

Mr_SC
Mr_SC

Posted on • Originally published at zelig880.com

How to use Props in VueJs

In this post we are going to explain how to use properties using the VueJs framework. The post expect a basic understand on the framework itself and will not cover the basic configurations.

First and foremost, we should introduced what Properties are in VueJs. My definition of props is:

VueJs properties are variables (static or Dynamic) that can be passed to a component from its parent.

VueJs Props definition

Properties are not unique to VueJs, in fact if you have ever used any other framework such as RectJs or Angular you have surely used them before.

When creating a component based architecture ( that is provided by VueJs and other frameworks), you need to have a way to pass information between components. Properties offer just such a feature.

A simple example of a property is showed below. Properties in VueJs can either be static (if the property name is not prefixed by “:”), or they can be dynamic and therefore being driven by an existing variable (either Data or computed).

<template>
  <div id="app">
    <Basic 
      staicValue="static string"

      :dynamicFromData="myValue"
      :dynamicFromComputed="myComputedValue"/>
  </div>
</template>

<script>
import Basic from "./components/Basic";

export default {
  name: "App",
  components: {
    Basic
  }
,
  data(){
    return {
      myValue: "A special string"
    }
  },
  computed:{
    myComputedValue(){
      return `${this.myValue}, really special `;
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

In the above example we are passing variables using three different methods. Simple string, value passed from the data and finally a computed property. It is important to know that variable can have different values. They can be boolean, string, integer, arrays, object and even methods (even if I do not suggest to do this in Vue).

Props definition

It is now time to start and really define how powerful Props are in VueJs and what you can do to really make the most fo this feature.

The following example are going to increase in complexity, so if you want to see the final result and see what I would suggest to be a very complete implementation of properties you can just hump at the ed of the page where you will also find a link to codesandbox.

Basic Props – Array

As you will learn in this article, Properties can be quite complex. But VueJs always allows us to slowly learn its powerful skills.

In the following example we are going to define properties without specifying any of its core values. This method of declaring properties is not really suggested for development, and it should be avoided if possible.

export default {
  name: "basicProperty",
  props: ['basic', 'property2', 'property3']
};
Enter fullscreen mode Exit fullscreen mode

In the above example we have declared 3 different properties, but they do not have any other information and the framework will not be able to know their type, if they are required, if they have a default value,etc.

Basic Props – Types

In the first example we have declared properties using a simple array of string. In the current code snippets, we are going to still keep things simple, but we will modify our declaration to be completed using an Object.

This small change, differently from the first example, will allow us to build up the complexity of our property overtime.

To be able to use the Object declaration, we also need to start and introduce a new feature of the Vue property “Type”.


export default {
  name: "basicObject",
  props: {
    value: String,
    age: Number,
    enabled: Boolean
  }
};
Enter fullscreen mode Exit fullscreen mode

In the example above, we have declared 3 different properties. This time we have defined a type for each of them. As you well know, Javascript is a loosely types language, and type declaratorio is usually only achieved with the use of external tools such as typescript.

VueJs provide a simple type declaration integration with its Properties. This is quite powerful (as you will also see later when we introduce validator), as it can support the user of the component in making good use of its variables.

The available types are:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Date
  • Function
  • Symbol

If you pass the wrong type to a component, Vue will NOT render the component and provide you a well defined error message.

Basic Props – Required

So far we are able to define endless properties and also assign types to it. In this paragraph we are going to introduce another feature called “required”. This feature will allow us to define required (or optional) properties within our component.

Failure to provide a required property will result in an error and the component will not be rendered.

export default {
  name: "required",
  props: {
    value: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      required: false
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

As you may have noticed, to be able to add further details to our property, we have been forced to change our propety to be an object itself.

If this is the first time that you look at this, it may look complicated, but if you continue to read things will soon start to make sense.

Providing a required string is very beneficial, as it will save you from having to write inline validation such as <div v-if="requireProp" :value="requiredProp" />.

Default

Adding a required props is great as it saves us the need to define lots of manual error checking, but what can we do if the value is not required?

Well, in this case we can use Default. In fact the use of default is actually suggested when the required flag is set to false. This will make sure that we are aware of the values that is being parsed by the template.

The default value must either be a nullable value, or it has to be in the correct type (so if a property is a string, the default need to be string too).


export default {
  name: "default",
  props: {
    value: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      required: false,
      default: null
    },
    label:{
      type: String,
      required:false,
      default: "Your name is"
    }
  }
};

Enter fullscreen mode Exit fullscreen mode

Before we move on, it is important for you to be aware that when declaring a default for Object or Array property, you will need to define it as a factory function:


    propObject: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    propObject: {
      type: Array,
      default: function () {
        return ['blue', 'red', 'orange']
      }
    },

Enter fullscreen mode Exit fullscreen mode

Please bear in mind that in years working in vue, I had to use the above very rarely, as it is not very common to have default complex types, as it is usually easier to use computed property to simplify the code.

Validator

Most of the components that you have probably seen around the internet and proposed in stack overflow, will probably have just the above mentioned features (type, required, default). In fact that is the most accepted props declaration.

In this section, I am going to introduce a very useful feature of the property called validator.

There are cases in which developer miss the opportunity to use Validator (I am usually guilty of this), by overthinking it and implementing complex computed properties. As with all the features mentioned so far, failing to pass the validator function will produce a nice and readable error ( much easier and safe that our own computed implementation.



export default {
  name: "Vaidator",
  props: {
    colour:{
      type: String,
      required: true, 
      validator: function (value) {
        return ['green', 'red', 'orange'].indexOf(value) !== -1
      }
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

The validator is declared as a function that will be fulfilled if its value returned is true. I usually would not suggest to add too much complexity into this, and make sure they include the minimum required logic.

Conclusion

VueJs is has gain great support for being so simple to use. But as shown in this article, it also provide its users with very powerful built in tools ready to be used.

Implementing properties as shown in this article, would really benefit your day to day development. A well defined implementation of properties (and all other features offered by Vue), not only will support you in speeding up development. It can also be used by error tools (like sentry) and/or other developers, but supporting them in using the component to its best.

Link to the codepen used to develop this article can be found here: https://codesandbox.io

Oldest comments (0)