簡體   English   中英

Vue.js 組件數據依賴於其他組件數據

[英]Vue.js component data depends on other component data

我有一個組件如下。

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

這個組件是一個圖片庫。 現在我有另一個組件,我需要在其中引用 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.
        };
     },
}

我想要達到的目標:

我希望其他組件的“imageIndex”是對 ImagesGallery 組件的“activeImageIndex”的引用。 如果我修改“imageIndex”,畫廊索引的值也應該改變。

我試圖在 data 函數中分配 imageIndex: this.$refs.gallery.activeImageIndex 但顯然它在這種情況下不起作用。

您需要將索引作為道具傳遞給子組件:

** 家長

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

** 孩子

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

在子組件中,您可以像以前一樣訪問activeImageIndex

您應該了解 VueJs 中的反應性、道具和v-model指令。 您應該使用 v-model 將imageIndex作為道具傳遞給子組件。 例如:

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

和一位家長:

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

要更改子組件中的imageIndex ,您應該調用:

this.$emit('input', newIndex)

要更改父組件中的imageIndex ,您只需分配它:

this.imageIndex = newIndex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM