[Vuejs]-How to define vue component prop structure without overriding it

0👍

Late to this question, your fiddle already does what you expect (based on the question).

I had a similar problem with props not working as I intended, the idea was to use components to allow the user to pick certain selections, in several places. The parent needs to display the values and read them back when something changes. I separated the component state from the parent prop state, something like:

Vue.extend({
    replace: true,
    template: '<span v-for="element in fromComponent"' +
            '<label>' +
                '<input type="checkbox" v-model="element.checked" /> {{ element.label }}' +
            '</label>' +
        '</span>',
    data: function () {
        return {
            fromComponent: [
                { label: 'First', checked: false },
                { label: 'Second', checked: false }
            ],
            busy: false
        };
    },
    props: {
        fromParent: {
            twoWay: true
        }
    },
    watch: {
        fromComponent: {
            handler: 'updateParent',
            deep: true
        },
        fromParent: {
            handler: 'updateComponent',
            deep: true
        }
    },
    methods: {
        updateParent: function () {
            var index, element;

            // Avoid an update loop
            this.busy = true;

            for (index in this.fromComponent) {
                element = this.fromComponent[index];

                // Map the component value to the proper prop value
                this.$set(['fromParent[', index, '].checked'].join(''), !!element.checked);
            }

            this.busy = false;
        },
        updateComponent: function () {
            var index, element;

            if (this.busy) {
                return;
            }

            for (index in this.fromParent) {
                element = this.fromParent[indicator];
                this.$set(['fromComponent[', index, '].checked'].join(''), !!element.checked);
            }
        }
    },
    ready: function () {
        // Set the component data to match the values from the parent
        this.updateComponent();
    }
});

Leave a comment