[Vuejs]-Selected values in a v-for loop of components

0👍

This depends on the relationship from your ‘Send Button’-component with your parent component.
You can either:

  • Use the $emit() method to propagate data up the component tree to the shared parent component. Then prop it down to the ‘Send Button’-component.
  • Have a single source of truth by using Vuex. This is a store that keeps all your data in a centralised object.

Perhaps you can provide us with more information on the project structure?

0👍

First of all, ask yourself if this component is being used anywhere else but here. If you only use it once, build it into the parent component and your problems are solved.
Otherwise I’d go with @laurensvm’s approach of using emit or Vuex.

0👍

After some researches on google i have founded a solution. I don’t know if it the right way but it works fine and it seems clean.

My solution consists to use emit on child component and v-model on parent like show following example.

<!-- 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}]
            },
            value: {
                type: Number
            }
        },
        data() {
            return {
                selectedProject: this.value
            }
        },
        methods: {
            changedValue(value) {
                this.$emit('input', value);
            }
        }

    }
    </script>

And on parent using an array variable on v-model.
Something like this:

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

See a runnable example clicking on codesandbox link below:

https://codesandbox.io/s/vue-template-4f9xj?autoresize=1&expanddevtools=1&fontsize=14&hidenavigation=1&moduleview=1

Leave a comment