NarūnasK
NarūnasK

Reputation: 4950

Infinite update loop in a component render function

I'm trying to understand how vue components work. The final goal is to add a line to the readonly textarea when I click my Go! button. At present I'm stuck with the following code:

// Register components
Vue.component('chatarea', {
  delimiters: ['${', '}'],
  props: ['msg'],
  template: '<textarea readonly="" rows="20">${msg}</textarea>',
})


// Create a root instance
var app = new Vue({
  el: '#app',
  delimiters: ['${', '}'],
  data: {
      messages: [
        'Hello from Vue!',
        'Other line...'
      ],
  },
  methods: {
    get_msg: function () {
      return this.messages.reverse().join('\n');
    }
  }
})

The following html is rendered in the way I want it - messages are displayed in reverse order:

  <div class="container" id="app">

    <div class="row">
      <div class="col-md-8 offset-md-2">
        <form action="/question" enctype="multipart/form-data" method="get" v-on:submit.prevent="onSubmit">
          <div class="input-group">
            <input type="text" class="form-control" placeholder="Say Something...">
            <span class="input-group-btn">
              <button class="btn btn-secondary" type="button">Go!</button>
            </span>
          </div>
        </form>
      </div>
    </div>

    <div class="row" style="">
      <div class="col-md-8 offset-md-2">
        <chatarea :msg="get_msg()"></chatarea>
      </div>
    </div>

  </div>

However I'm getting the following warning:

[Vue warn]: You may have an infinite update loop in a component render function.

I understand I'm doing something wrong... Here's JSFiddle

Upvotes: 3

Views: 6735

Answers (1)

Bert
Bert

Reputation: 82439

Your template calls get_msg which recalculates the reversed message array which causes the template to re-render and call get_msg, etc.

Instead, use a computed.

computed:{
  reversedMessages(){
      return this.messages.slice().reverse().join('\n');
  }
},

And change your template to

<chatarea :msg="reversedMessages"></chatarea>

Example.

Upvotes: 5

Related Questions