Home » vue » How can i pass a parameter to a Vue component?

How can i pass a parameter to a Vue component?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I just got started to Vue and i’m trying to understand some basic concepts such as conditional rendering and how to pass data from where i load the app to a component. Suppose i’m rendering a Vue component like this:

<div id="app">
    <myComponent></myComponent>
</div>

Suppose myComponent looks like this:

<template>
  <div>
  
    <h1>First block</h1>

    </h1>Second block</h1>

  </div>
</template>

I want to be able to render First block or Second block when i load the Vue app according to a parameter i pass to the component, like:

<div id="app">
    <myComponent id="first"></myComponent>
</div>

In this case i should see First block, whereas if instead of id="first" there was id="second" the output was supposed to be Second block. How can i do this?

I know it’s a very basic question, but most of the sources i found explained how to do the opposite. Any kind of advice is appreciated!

Answers:

In vue you could pass props (parameters) to component which defines this ones in its script like :

<template>
  <div>
  
    <h1 v-if="block==='first'">First block</h1>

    </h1 v-else>Second block</h1>

  </div>
</template>

<script>
export default{
  props:{
    block:{
       type:String, 
        default:'first'
     }
  }
}
</script>

in parent component pass the prop like :

<div id="app">
    <myComponent block="first"></myComponent>
</div>

or

<div id="app">
    <myComponent block="second"></myComponent>
</div>