首页 > 解决方案 > 组件的 v-for 循环中的选定值

问题描述

我实现了一个内部有一个选择元素的组件,它或多或少类似于以下内容:

<!-- child component -->
    <template>
        <b-form-select 
            v-model="selectedProject"
            :options="projects"
            @change="changedValue">
            <template v-slot:first>
                <option :value="null" disabled>-- Please select a project --</option>
            </template>
        </b-form-select>
    </template>

    <script>
    export default {
        name: 'AllocationItem',
        props: {
            projects: {
                type: Array,
                default: () => [{ value: Number}, { text: String}]
            }
        },
        data() {
            return {
                selectedProject: null,
            }
        },
        methods: {
            changedValue(value) {
                this.selectedProject = value;
            }
        }

    }
    </script>

我在父组件中使用此组件,可以在其中添加其他 AllocationItem 单击按钮。

为此,我使用了一个数组,每次点击添加按钮时我都会推送一个新项目(我不知道这是否是正确的方式......)

遵循父组件代码:

<!-- parent component -->
    <template>
        <b-button class="btnAction" @click="addItem()">Add</b-button>
        <b-button class="btnAction" @click="sendAllocation()">Send</b-button>
        <b-row v-for="allocation in resourceItem.allocations" v-bind:key="allocation.id">
            <allocation-item v-bind:projects="projects"></allocation-item>
        </b-row>
    </template>


    <script>
        export default {
        name: 'Management',
        components: {
            AllocationItem
        },
        data() {
            return {
                allocations: []
            }
        },
        methods: {
            addItem() {
                this.allocations.push(AllocationItem);
            },
            sendAllocation() {
                this.allocations.forEach((allocation) => {
                    // I WOULD LIKE TO HAVE ALL SELECTED VALUE HERE!!!
                });
            },
        },
        created() {
            const dataProjects = this.getProjectsData();
            dataProjects.then(response => {
                this.projects = response.map((item) => {
                    return {value: item.id, text: item.name}
                })
            });
        }
    </script>

在我的应用程序中,我有另一个按钮,发送按钮,应该读取在所有子组件(分配项)中选择的值。

我该怎么做才能拥有一个具有该选定值的数组?

提前谢谢大家

标签: javascriptvue.jsvuejs2frontendvue-component

解决方案


首先,问问自己这个组件是否在除此处以外的其他任何地方使用。如果你只使用一次,把它构建到父组件中,你的问题就解决了。否则我会选择@laurensvm 的使用 emit 或 Vuex 的方法。


推荐阅读