Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Adam Biro
Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Blog Post

[3] Data, Props, and Computed modifiers of Vue OptionsAPI

February 26, 2022 IT, Programming, Vue
[3] Data, Props, and Computed modifiers of Vue OptionsAPI

OptionsAPI is a VueJS term. It refers to all functions and properties like Data, Props, Computed, and many others that can behave as modifiers of a component. You will declare these modifiers between the script tags section inside the create app object. In this note, I am going to write about the Data, Props, and Computed modifiers of the options API. It is worth mentioning that modifier is not an official term. I made it up because of the purpose of these properties.

Vue.createApp({
   // you will define the options API here
}).mount('#app')

What are the Data modifier of Options API ?

The official definition of the data property is “A function that returns the initial reactive state for the component instance.” So in that object, you declare the default values of your component that you will be able to access with the ‘this’ keyword outside the data method but inside in the create app object.
We can pass the properties of the data method to child components. In this case, the parent Data definition becomes the definition of a Prop in the child component. You can read here more about data methods.

What are Props of Options API?

  • Passed Data to a child component is called Props.
  • It is like custom attributes for our components.
  • The purpose of the props to customize the behavior of our component similarly to how HTML attributes change the behavior of an element.
Pass data to components with props. Eg from the root component to the child components.

How to pass data downwards the hierarchy chain?

  • Define a Data property at the parent level
  • Define it as Props in the child level
<template>
  <h3>Heyy!</h3>
  <greeting :age="age"></greeting>
  <user :age="age"></user>
</template>
<script>
// Import components locally in VueJS
import Greeting from "@/components/Greeting.vue";
import User from "@/components/User";
// Vue common code section
export default {
  name: "App",
  components:{
    Greeting,
    User
  },
  data(){
    return{
      age: 20
    }
  }
}
</script>

This is the code of the parent App component.

<template>
  <p v-if="age > 25">{{ msg }}</p>
  <p v-else>You must be 25 years or older to view this message</p>
</template>
<script>
export default {
  name: "Greeting",
  data(){
    return {
      msg: "Hello test"
    }
  },
  props:["age"]
}
</script>

This one is for the child Greeting component.

<template>
  <p>The user is {{age}} years old</p>
</template>
<script>
export default {
  name: "User",
  props: [
      "age"
  ]
}
</script>

This is the code of the child User component.

How to validate props? Why is it important?

Validating props help you to debug the application. It forces the parent component to pass the proper data type to the component. This way we can catch and prevent the error before shipping the application. 

To be able to validate props you need to convert the props array to an object. In the object you can define several properties like default, required, etc … You can see the options below as guidance:

// code above 
... 
  // props: [
  //     "age"
  // ],
  props: {
    age: {
      // All JavaScript data type is allowed to use like: String Number, Boolean, Array, Object, Date, Function, Symbol,
      type: Number,
      //required: true
      // default: 20 // if the type is an array or object the default has to be a function with returning data type
      validator(value) {
        console.log(value)
        if(value < 130) {
          return true
        }
        console.error('you can\'t be older than 130 years old' );
      }
    }
  },
...
// code below 

Computed modifiers in Options API!

  • It is a dynamic property.

How do we define a Computed property?

<div id="app" v-cloak>
    <p>{{ fullName }}</p>
</div>

We refer to it as a property in the HTML template.

const vm = Vue.createApp({
    data() {
        return {}
    },
    methods: {},
    computed: {
        fullName() {
            console.log('this is a computed call')
            return `${this.firstName} ${this.lastName.toUpperCase()}`
        },
    }
}).mount('#app')

But we define it as a method in the computed options block

Why do we need this if it seems to work as a method?

  • It does not behave the same as a method.
  • Calling the method section will reload the page. So all the defined functions will be executed even if we call a different method.
  • Computed property change is not reloading the page. 
    • So it will not cause any side effects as the methods do.
    • We save execution time.
    • The performance will be better.
    • Vue calls the computed property functions internally.
  • Vue stores the computed properties, not the function.
    • That’s why we can see this in the Vue devtool as output.
Computed property in the Devtool
  • We can’t pass a value to computed properties
    • We do not use parenthesis in the HTML either
    • If you need to pass params to a computed property then you need to write a method! Not a computed property!
  • For more details check this video:

When should we use computed property ?

  • When you would like to write a function that calculates a value then you should write a computed property.

Conclusion & Closing

This topic continued my previous VueJS basics notes about Interpolations, Directives, and Components in VueJS. In this one, I wrote about the Options API in VuJS 3 specifically the data, props, and computed methods option. When and why are they useful. Next time I am going to continue with the rest of the modifiers.

Taggs: