To pass dynamic props in Vue we make use of v-bind
. If the props are not bind using v-bind
, it treats the values as static values i.e, it interprets it as strings.
For example,
<MyComponent subscribed="333" />
Here, subscribed is passed as static value. If you want Vue to treat it as a Javascript expression, use v-bind
.
<MyComponent v-bind:subscribed="333" />
or using shorthand:
<MyComponent :subscribed="333" />
Let’s look at dynamic props in more details by creating a Vue CLI application.
vue create dynamic-props
Once, the installation is complete, you can navigate to the folder and run the server to load the application.
❯ cd dynamic-props
❯ npm run serve
Next, we will create a file EmployeeList.vue
within the src/components
folder of the project.
❯ touch src/components/EmployeeList.vue
We will make use of EmployeeList
component to list employee details in a company.
// EmployeeList.vue
<template>
<h2>Employee Details</h2>
</template>
<script>
export default {
name: 'EmployeeList'
}
</script>
Let’s include this component in the App.vue
. For simplicity, we will delete all the default code in the App.vue
file and rewrite it.
// App.vue
<template>
<EmployeeList />
</template>
<script>
import EmployeeList from './components/EmployeeList.vue'
export default {
name: 'App',
components: {
EmployeeList
}
}
</script>
Let’s open the link http://localhost:8080/
Since we want to pass dynamic props, let’s create some data in the App
component and pass it to EmployeeList
component.
// App.vue
<template>
<EmployeeList />
</template>
<script>
import EmployeeList from "./components/EmployeeList.vue";
export default {
name: "App",
components: {
EmployeeList,
},
data() {
return {
employees: [
{
id: 1,
name: "Mickey",
},
{
id: 2,
name: "Donald",
},
],
};
},
};
</script>
Now, using v-bind
we can pass employees
properties id
and name
to the EmployeeList
component.
// App.vue
<template>
<div v-for="employee in employees" :key="employee.id">
<EmployeeList :id="employee.id" :name="employee.name" />
</div>
</template>
In this example, we are passing the dynamic props id
and name
using v-bind
. Notice, we have used the shorthand for v-bind
.
If we do not bind the props, Vue will treat them as static props.
<template>
<div v-for="employee in employees" :key="employee.id">
<EmployeeList id="employee.id" name="employee.name" />
</div>
</template>