[Vuejs]-Vue pass custom component as a property to parent component

1👍

I would use slots to place the PictureInput component into the Card component. I removed some HTML for a simplified example.

Card.vue

<template>
  <div class="card is-size-7-mobile is-fluid">
        <div class="card-header">
            <a class="card-header-title">

                <!-- Don't need to use "this" keyword inside the template,
                it is implied that the context is already "this" -->
                <span class="is-info" @click="isExpanable = !isExpanable">{{title}}</span>
            </a>
        </div>
        <div v-if='isExpanable'>
            <slot/> <!-- Slot where the <PictureInput/> will be inserted -->
        </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      isExpanable: false, // internal state to manage the open/close toggle
    }
  },
  props: {
    title: String, // Define the data type
  }
};
</script>

<style scoped>
.card {
  border-radius: 1em;
  background-color: transparent !important;
  border-color: transparent !important;
}
.card-header {
  box-shadow: transparent;
}
</style>

ImageInput.vue

<template>
<div class="content">
    <Card :title="makeCardTitle">
        <PictureInput/>
    </Card>
</div>
</template>

<script>
import PictureInput from 'vue-picture-input';
import Card from './Card';

export default {
    name: 'ImageInput',
    components: {
        PictureInput,
        Card
    },
    props: {
        idx:{
            type:Number,
            default: 0
        }
    },
    computed: {
        // Should be a computed property since we are creating data from internal data "idx"
        makeCardTitle: function(){
            return "page ".concat(String(this.idx));
        }
    }
}
</script>

Hopefully this guides you in the right direction. Also, you shouldn’t have to instantiate with Vue.extend(PictureInput). Usually, all you need to do is add it to the components option key.

Leave a comment