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

标签 javascript vuejs2

我正在尝试了解 vue 组件的工作原理。最终目标是在我单击 Go 时向只读 textarea 添加一行!按钮。目前我坚持使用以下代码:

// 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');
    }
  }
})

以下 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>

但是我收到以下警告:

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

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

最佳答案

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

相反,使用计算。

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

并将模板更改为

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

Example .

关于javascript - 组件渲染函数中的无限更新循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44075085/

相关文章:

javascript - Vue.js 动态组件不会改变

javascript - YQL-描述 : undefined

javascript - Graphael 文档、最近的示例等

javascript - 在组件端删除导入的 CSS

css - 如何在for循环中的vue中设置css类?

html - 为 bootstrap-vue 轮播图像添加背景颜色

javascript - 将 Django 模板中的 JSON 传递到独立的 Javascript 文件

javascript - 对 AngularJS 中的复选框值进行排序

javascript - react 路由器: Cannot GET with email address as params

vuejs2 - Vue : Binding radio to boolean