Categories:Viewed: 47 - Published at: 3 months ago

Introduction

Vue is a JavaScript framework that allows developers to create components that are used to divide the user interface into smaller pieces, rather than building the entire UI in a single file. When using components, we may want to pass data down from the parent component to the child component at some point, this is usually done with properties, also known as props.

In this guide, we will take a deep dive into props, we'll take a look at how props work, the various prop types, how to pass various forms of data, and lots more.

What Are Props?

Props can be a crucial concept to understand when working with components in Vue. Props, which stands for properties, enable us to pass data and functionality from one component to another. It's important to understand that props dataflow is one directional - we can pass data only from a parent to a child component, not another way around.

Note: Props are read-only, which means the child component cannot modify them because the data is owned by the parent component and is only passed down to the child component to read it.

Declaring Props in Vue

Registering props is simple; all we have to do is add it to the props array in the <scripts> tag. Then, we can use it in our app's <template> section. This occurs in the child component, where data is received from the parent component:

<template>
  <p>{{ name }}</p>
</template>

<script>
export default {
  props: ['name']
}
</script>

This is the Single File Component syntax. Alternatively, you can register props for a specific component via:

Vue.component('user-profile', {
  props: ['name'],
  template: 'My name is {{ name }}'
});

Declaring Multiple Props in Vue

props are an array - you can add as many as you'd like:

<template>
  <p>My name is {{ name }} and I am {{ age }} years.</p>
</template>

<script>
export default {
  props: [
    'name', 
    'age'
  ],
}
</script>

Props Value Types

So far, we have only passed string values, but, in reality, any data type can be passed as a prop - including numbers, objects, arrays, Boolean, methods, dates, and so on.

Note: When we use a static method to pass a number, object, array, and boolean values, we must bind them to tell Vue that this is a JavaScript expression rather than a string (matching the method's name).

So, to pass them, we pass them as a JavaScript expression (wrapped in quotes), which is evaluated to the correct data type implicitly:

<template>
  <userprofile :age="22">
  <userprofile :married="false">
  <userprofile :hobbies="['Singing', 'Gaming', 'Reading']">
  <userprofile :name="{
      firstName: 'John',
      lastName: 'Doe'
    }">
</userprofile></userprofile></userprofile></userprofile></template>

However, implicit conversions aren't without fault in practical settings. In most cases - you'll want to specify the types explicitly.

Specifying Props Types Explicitly

Knowing that we can pass any type of data as a prop, the best practice is to specify the type of prop we want to use by declaring them as part of an object rather than an array, and to explicitly specify the type of that value. This is useful because Vue sends a warning alert (in development mode) to the console if the type of data passed does not match the specified prop type:

<template>
  <p>My name is {{ name }} and I am {{ age }} years.</p>
</template>

<script>
export default {
  props: {
    name: String,
    age: Number,
  }
}
</script>

Passing Props Into Components

Passing props into components in Vue is similar to passing HTML attributes into HTML tags, and this can accept all types of data, including methods. For example, if we have a profiles component and want to pass user details into the user component, we can do something like this:

<template>
  <userprofile v-bind:name="user.name" :img="user.image">
</userprofile></template>

Static and Dynamic Props

Props can be passed in one of two ways: as a static value or as a dynamic value. By static, we mean that these values are passed directly into the component without the need for v-bind or : (semicolon):

<template>
  <userprofile name="John Doe">
</userprofile></template>

While for dynamic values we use the v-bind or its : shortcut:

<template>
  <userprofile :name="name">
</userprofile></template>

<script>
export default {

  data() {
    return {
      name: 'John Doe'
    }
  },

}
</script>

Dynamic values may be inherited from the data() option of our component script.

Passing Props With Ternary Operators

Oftentimes we want to pass different data based on the value of a condition. In that case, the ternary operator comes in handy, because we can use it inside a prop value:

<template>
  <div id="app">
    <home :title="isHomepage? 'Welcome to the homepage' : 'This is not the Homepage'">
  </home></div>
</template>

<script>
import Home from './components/Home'
export default {

  data(){
    return{
      isHomepage: true,
    }
  },
  components: {
    Home
  }
}
</script>

In this example, we've checked the loggedIn value - since it is true (a user is already logged in) the resulting prop value will be Log Out.

Passing Methods as Props

It is also possible to pass methods as props down to a child component, which works similarly to passing other data types:

<template>
  <childcomponent :method="myFunction">
</childcomponent></template>

<script>
export default {

  methods: {
    myFunction() {

    }
  }
};
</script>

Working With Props

As previously stated, the primary goal of using props is to pass down data. Say we are building an app that will be displaying user details - we will prefer to create reusable components so that we can pass these data as props, rather than manually creating separate component for each user. Let's create a parent component for that app:

<template>
  <div id="app">
    <userprofile :name="userName" age="22">
    <userprofile :name="userName" age="18">
    <userprofile :name="userName" age="27">
  </userprofile></userprofile></userprofile></div>
</template>

<script>
import UserProfile from './components/UserProfile'

export default {

  data(){
    return{
      userName:"John Doe",
    }
  },
  components: {
    UserProfile
  }
}
</script>

And here's what the child component will look like:

<template>
  <div>
    <h2>My name is {{name}} and I am {{age}} years old.</h2>
  </div>
</template>

<script>
export default {

  props:{
    name:String,
    age:Number,
  }
}
</script>

Validating Props

Previously, we saw that adding prop types helps check the type of data returned by the props, which is a way to validate the props, but we can also add the required key and its value to the prop, as shown below:

props: {
  name: {
    type: String,
    required: true
  }
}

Setting Default Prop Values

In some cases, we may want to set default values so that if the child component is unable to get data from the parent component, such data can be rendered:

props: {
  studentUserName: {
    type: String,
    required: true,
    default: "student##"
  },
  studentPassword: {
    type: String,
    required: true,
    default: "password123"
  },
  userImg: {
    type: String,
    default: "../default-avatar.jpg"
  },
},
Note: The default value can also be an object or a method that returns a value.

Conclusion

Props are a crucial part of Vue when using components. In this article, we've taken a look at what props are, how to use them in Vue, how to declare and register them, set default values, validate them, etc.

Reference: stackabuse.com

TAGS :