vuejs3element-plus

In Vue3 + element-plus, how to pass a component with arguments to another component as a prop


Vue beginner here.

I have a simple custom component:

MaterialIcon.vue:

<script lang="ts">
export default {
  props: ['iconname']
}
</script>

<template>
  <span class="material-icons-outlined md-18">{{iconname}}</span>
</template>

And, as per element-plus docs (https://element-plus.org/en-US/component/button.html#button-attributes), I want to pass it as a component to be used as an icon in a button. How to get this done, specially considering my custom component has an argument?

<el-button type="primary" title="Refresh" :icon="???"/>

the below works, but the problem with that solution is that the loading feature (which replaces the icon with a spinner) appears on the side of my custom icon, if I do that (instead of replacing the icon, as it should). Also, it would be pointless to have a component with that approach - with that approach, I could just use the one-liner syntax in my component definition instead.

<el-button type="primary" title="Refresh">
  <material-icon icon_name="refresh"/>
</el-button>

Solution

  • Use Slots if you want to put something inside a component.

    The Element+ Button component has 3 Slots

    So, if you want to replace the icon, then use the icon slot.

    <template #icon>
       <material-icon iconname="refresh"/>
    </template>
    

    Check the Docs about the slots.

    Pay attention to your icon_name attribute. It should not have the underline symbol, if your Prop does not have it.

    For Naming/Using Props check the Prop Passing Details