2

I have a vue component that is page.vue. And I have a child vue component that is card.vue as shown below.

I can't get it to work with injecting data into the card(child) component.

I tried injecting data inside and in the data function for the page component.

Page.vue

<template>
  <div class="container">
    <card></card>
  </div>
</template>

<script>
import Card from "../Card.vue"
export default {
    name: 'skills',
    components: {
      "card": Card
    },
    data: function() {
        return {
            message: "Skills"
        }
    }
}
</script>

Card.vue

<template>
  <div class="container drop-shadow">
  </div>
</template>

<script>
export default {
    name: 'card',
    data: function() {
        return {
            data: "",
        }
    }
}
</script>

I want that card is reusable from other components also other than Page.vue. Need to inject data into card respective to where it is displayed.

1 Answer 1

3

There are two ways that you can pass data down.

The first is through the use of props.

METHOD 1:

<template>
  <div class="container">
    <card :message="message"></card>
  </div>
</template>

<script>
import Card from "../Card.vue"
export default {
    name: 'skills',
    components: {
      "card": Card
    },
    data: function() {
        return {
            message: "Skills"
        }
    }
}
</script>

This will make the data available in Card.vue

<template>
  <div class="container drop-shadow">{{ message }}
  </div>
</template>

<script>
export default {
    name: 'card',
    props: ['message'],
    data: function() {
        return {
            data: "",
        }
    }
}
</script>

METHOD 2: You could also put a slot in Card.vue which will allow you to put content in between the element tags on the parent like so. Page.vue

<template>
  <div class="container">
    <card>{{ message }}</card>
  </div>
</template>

<script>
import Card from "../Card.vue"
export default {
    name: 'skills',
    components: {
      "card": Card
    },
    data: function() {
        return {
            message: "Skills"
        }
    }
}
</script>

Card.vue

<template>
  <div class="container drop-shadow">
    <slot />
  </div>
</template>

<script>
export default {
    name: 'card',
    data: function() {
        return {
            data: "",
        }
    }
}
</script>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I got it to work. But I can't get it to work with passing of an object. What am I missing?
You’ll have to be more specific
I'm not sure what you mean by passing an object. Do you mean an actual javascript Object? Why are you passing an object?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.