[Vuejs]-VueJS – get input values from a recursive tree

1👍

One way of doing this is to pass a prop down from TreeComponent to each node.

<template>
  <div class="tree">
    <ul class="tree-list">
        <tree-node :node="treeData" :form="formRepo"></tree-node>
    </ul>
  </div>
</template>

Then each node passes the prop down to its children.

 <node v-for="child in node.children" :node="child" :key="child.id" :form="form"></node>

This way each node will have a direct reference to the TreeComponent.

In each node you can watch the model and update the form prop. You need to use your child.id so you know which field is which.

Your formRepo can be a fully fledged object, but a hash could work just as well.

data() {
    return {
        treeValues: [],
        formRepo: {
        }
    };
}

Note: if you want formRepo to be reactive you’ll need to use Vue.set to add new keys to it.

0👍

Thank you for your answer.

I managed to solve it by posting the data to the server on every change, since this was a handy feature.

The way I did so was:

Call function from the input (same call for text inputs)

<input
    type="radio"
    class="form-check-input"
    :name="'parent-' + node.parent_id"
    :id="node.id"
    @input="change($event, node.id, node.parent_id)"
/>

Have some data variables to fill (Route is required for the axios request)

data() {
    return {
        input: {
            id: null,
            parentId: null,
            radio: false,
            value: null
        },
        route: null
    };
},

And then some magic. The change method. (Left the axios bit out.)

methods: {
    change: function(event, id, parentId) {
        this.input.parentId = parentId;
        this.input.id = id;

        if (event.target.value === "on" || event.target.value === "off") {
            this.input.radio = true;
            this.input.value = event.target.value === "on" ? true : false;
        } else {
            this.input.value = event.target.value;
        }

        if (this.input.value) {
            axios.put().then().catch()
        }
    }
}

I know there is some room of improvement in the validation bit. If a user enters ‘on’ in a text field, this will probably fail. So there is work to be done, but the basic filling of a form is working.

As to if this is the best way, I have no clue, since I’m new to Vue.

👤nepp95

Leave a comment