Vue仅使v-for中的一个特定组件对prop做出反应而不对其他组件做出反应

时间:2019-07-01 09:18:50

标签: vue.js vue-component

issue:Vuejs,有一个在v-for循环中在父内部呈现的组件(文件上传)。我向其传递了一个道具,以有条件地渲染一个删除按钮(基本上是从div类的预览中删除背景)。我如何仅使该循环中的特定组件对show / hide道具做出反应而不对其他组件做出反应? 例如。 v-for渲染了3个FileUpload组件。所有人都有isRemoveBtnShown道具。如何使FileUpload1显示按钮,而使FileUplod2 and 3不显示?

父母:

<FileUpload v-for="(field, index) in uploadFieldsToRender"
                    ref="file-upload"
                    :key="field"
                    :docPageTitle="field"
                    :isLoading="isLoading"
                    :shouldDocsBeScanned="shouldDocsBeScanned"
                    :isUploadError="isUploadError"
                    :isRemoveBtnShown="isRemoveBtnShown"
                    @fileUpload="handleFileUpload"
                    @fileRemoval="handleFileRemoval"
                    @fileScan="handleFileScan"
                    @fileUploadMounted="onFileUploadMounted"
                />

文件上传:

        <div v-else class="controls">
            <button
                v-if="shouldDocsBeScanned"
                class="button btn-scan"
                @click="() => $emit('fileScan', this.$refs)"
            >
                <span class="btn-icon"></span>
            </button>
            <div v-if="true" class="upload-options">
                <label>
                    <input
                        type="file"
                        class="image-upload"
                        accept="image/*, application/pdf"
                        @change="$event => this.$emit('fileUpload', $event, this.$refs)"
                    />
                </label>
            </div>
            <button
                v-if="isRemoveBtnShown"
                class="button btn-remove"
                @click="() => this.$emit('fileRemoval', this.$refs)"
                >
                <span class="btn-icon"></span>
            </button>
        </div>

道具:

        shouldDocsBeScanned: {
            type: Boolean,
            default: false
        },
        isRemoveBtnShown: {
            type: Boolean,
            default: false
        },

不能使用$refs,因为它们没有反应性(可以检查cmp是否有背景) 非常感谢!

1 个答案:

答案 0 :(得分:0)

想出了一种方法来解决我的问题,方法是 1)将isRemoveBtnShown本身移至FileUpload 2)将FileUpload的{​​{1}}作为父项中的ref cmp,然后通过field来获取当前组件,并将其内部属性(this.$refs[field])更改为希望的。

以魅力形式工作,不会影响兄弟姐妹isRemoveBtnShown