How to pass props dynamically to dynamic component in Vue.js?

Sometimes, we want to pass props dynamically to dynamic component in Vue.js.

In this article, we’ll look at how to pass props dynamically to dynamic component in Vue.js.

How to pass props dynamically to dynamic component in Vue.js?

To pass props dynamically to dynamic component in Vue.js, we can check the current component being rendered in component and pass in the props accordingly.

For instance, we write

<template>
  <component :is="currentComponent" v-bind="currentProps"></component>
</template>

<script>
export default {
  //...
  data() {
    return {
      currentComponent: "myComponent",
    };
  },
  computed: {
    currentProps() {
      if (this.currentComponent === "myComponent") {
        return { foo: "baz" };
      }
    },
  },
  //...
};
</script>

to check the value of currentComponent in the currentProps` computed property.

And we return an object with the props we want to pass into the child component.

In the template, we add the component component to render the component that’s set with the name as the value of the is prop.

And we set the v-bind directive to currentProps to pass the properties inside the object as props.

Conclusion

To pass props dynamically to dynamic component in Vue.js, we can check the current component being rendered in component and pass in the props accordingly.