0

Here is my code, and i try to get fruit1 and fruit2 input, but got [object Object] or undefined with alert(this.inputs.id) or alert(this.inputs).

<div id="item">
    <div v-for="input in inputs" :key="input.id">
        <label :for="input.id">{{input.label}}</label>
        <input :id="input.id" v-model="input.value"></input>
    </div>
    <button @click="addInput">Add input</button>
</div>

data() {
    return {
        counter: 1,
        inputs: [{
            id: 'fruit1',
            label: 'Enter Fruit Name',
            value: '123',
        }],
    }
}

addInput() {
    this.inputs.push({
        id: `fruit${++this.counter}`,
        label: 'Enter Fruit Name',
        value: '',
    });
}
3
  • this.inputs is an array not object, you can't call this.inputs.id, but this.inputs[0].id Commented Nov 26, 2018 at 4:38
  • Where are you trying to call alert()? Commented Nov 26, 2018 at 4:41
  • @ChristhoferNatalius I got it, many thanks with your answer this.inputs[1].id Commented Nov 26, 2018 at 4:47

1 Answer 1

1

addInput should be put on methods

this.inputs is an array not object, you can't call this.inputs.id, you should do this.inputs[0].id instead

if you want to get certain input by providing the id, you can do this

methods: {
    addInput() {
        this.inputs.push({
            id: `fruit${++this.counter}`,
            label: 'Enter Fruit Name',
            value: '',
        });
    },
    getInput(id) {
        return this.inputs.find(input => {
            return input.id === id
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.