Alastair_Handler
Alastair_Handler

Reputation: 23

Why does my vue.js button not create a new textarea?

I am working on my first Web App using vue.js and I want to have a button that will create a new textarea when clicked. It seems to work fine when I checked it at jsfiddle, but when I load it in visual studio and run it, I do not get any results and the textarea and button do not display.

<!-- HTML -->
<div id="column1" style="float:left; margin:0; width:25%;">
            <h4>Column Header</h4>
            <div id="tile">
                <input type="button" value="+" @click="addInput">
                <div class="inputArea" v-for="input in inputs" :key="input.id">
                    <textarea placeholder="Enter text... " :id="input.id" v-model="input.value"></textarea>
                </div>
            </div>
        </div>


/* Vue.js on my main.js */
var tile = new Vue({
    el: '#tile',
    data: {
        counter: 0,
        inputs: [{
            id: 'text0',
            value: '',
        }],
    },
    methods: {
        addInput() {
            this.inputs.push({
                id: 'text${++this.counter}',
                value: '',
            });
        }
    }
});

I expected a textbox to be created each time the button is pressed. The textbox should appear beneath the previous one. What is happening though is I don't see either the button or any textboxes. Thanks in advance for taking the time to consider this!

Upvotes: 2

Views: 242

Answers (1)

BorisTB
BorisTB

Reputation: 1806

data property must be a function (returning object). Otherwise it's initialised only once on first render.

Change it to this and it should work:

data() {
  return {
    counter: 0,
    inputs: [{
      id: 'text0',
      value: '',
    }],
  }
}

And also, when using template literals, you have to use back-ticks ( ` ), so the method should be:

addInput() {
  this.inputs.push({
    id: `text${++this.counter}`,
    value: '',
  });
}

Upvotes: 1

Related Questions