组件渲染函数中的无限更新循环

Nar*_*asK 3 javascript vuejs2

我试图了解vue组件是如何工作的。textarea最终目标是当我单击 Go! 时向只读添加一行。按钮。目前我被以下代码困住了:

// 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');
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

以下内容html按照我想要的方式呈现 - 消息以相反的顺序显示:

  <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>
Run Code Online (Sandbox Code Playgroud)

但是我收到以下警告:

[Vue warn]:组件渲染函数中可能存在无限更新循环。

我知道我做错了什么......这是JSFiddle

Ber*_*ert 5

您的模板调用get_msg会重新计算反向消息数组,这会导致模板重新渲染并调用get_msg等。

相反,使用计算的。

computed:{
  reversedMessages(){
      return this.messages.slice().reverse().join('\n');
  }
},
Run Code Online (Sandbox Code Playgroud)

并将您的模板更改为

<chatarea :msg="reversedMessages"></chatarea>
Run Code Online (Sandbox Code Playgroud)

例子