0

I have a component as follows.

export default {
    name: "ImagesGallery",
    data () {
        return {
            activeImageIndex: 0,
        };
    },
}

This component is a gallery of images. Now I have another component in which I need to refer to the activeImageIndex.

<template>
    <div>
        <images-gallery ref="gallery">
    </div>
</template>

export default {
     name: "AnotherComponent",
     components: {
         ImagesGallery,
     },
     data () {
        return {
            imageIndex: null, // I want this to refer to the images gallery index.
        };
     },
}

What I want to achieve:

I want the "imageIndex" of the other component to be a reference to the "activeImageIndex" of the ImagesGallery component. If I modify "imageIndex", also the value of the gallery index should change.

I tried to assign imageIndex: this.$refs.gallery.activeImageIndex in the data function but obviously it doesn't works in this context.

2 Answers 2

1

You need to pass the index to the child component as a prop:

** PARENT

<images-gallery :activeImageIndex="imageIndex" ref="gallery">

** CHILD

export default {
    name: "ImagesGallery",
    props: {activeImageIndex: Number} 
}

In the child component you can access activeImageIndex the same way as you did previously.

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

Comments

1

You should learn about reactivity, props and the v-model directive in VueJs. You should pass imageIndex to a child component as a prop using v-model. For instance:

export default {
    name: "ImagesGallery",
    props: {
      value: Number // this prop represents **imageIndex** from a parent component.
    }
}

and a parent:

<template>
    <div>
        <images-gallery ref="gallery" v-model="imageIndex">
    </div>
</template>
...

To change imageIndex in the child component you should call:

this.$emit('input', newIndex)

To change imageIndex in the parent component you can just assign it:

this.imageIndex = newIndex

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.