NarūnasK
NarūnasK

Reputation: 4950

Declare reactive data properties in vue.js?

I have a very basic vue.js app:

var app = new Vue({
  el: '#app',
  delimiters: ['${', '}'],

  data: {
    messages: [
      'Hello from Vue!',
      'Other line...'
    ]
  }

})

The following html works fine:

  <div class="container" id="app">
    <div class="row" style="">
      <div class="col-md-8 offset-md-2">
        <span v-for="msg in messages">${msg}</span>
      </div>
    </div>
  </div>

However very similar html block does not:

  <div class="container" id="app">
    <div class="row" style="">
      <div class="col-md-8 offset-md-2">
        <textarea id="chat_area" readonly="" rows="20">
          <span v-for="msg in messages">${msg}</span>
        </textarea>
      </div>
    </div>
  </div>

[Vue warn]: Property or method "msg" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

I'm using Vue v2.3.3. What could be the problem?

Upvotes: 2

Views: 4980

Answers (1)

Luke
Luke

Reputation: 2400

As documentation says, interpolation in textareas won't work, so you need to use v-model.

If the only thing you want to do is to display html inside textarea, you could in theory use an ugly workaround by wrapping your array fields inside a function and set that function as textarea v-model:

var app = new Vue({
  el: '#app',
  delimiters: ['${', '}'],
  data: {
    messages: [
      'Hello from Vue!',
      'Other line...'
    ]
  },
  computed:{
    multiLineMessages: function(){
      var result = "";
      for(var message of this.messages){
        result += '<span>' + message + '</span>'
      }
      return result;
        }
    }
});

template part:

<div class="container" id="app">
    <div class="row" style="">
      <div class="col-md-8 offset-md-2">
        <textarea v-model="multiLineMessages" placeholder="add multiple lines">
        </textarea>
      </div>
    </div>
  </div>

It's more like a proof that it's doable but I highly don't recommend using it anywhere, as html shouldn't be generated this way (especially larger chunks of it).

jsFiddle preview

Upvotes: 3

Related Questions