user9993
user9993

Reputation: 6180

Updating a value when v-model changes

I have a text input with v-model binding it's value to data. I would also like to be able to call my parse() function when this v-model value changes in order to update an array that is also on data.

<div id="app">
    <input
        id="user-input"
        type="text"
        v-model="userInput">

   <ul id="parsed-list">
      <li v-for="item in parsedInput">
          {{ item }}
      </li>
    </ul>
</div>

new Vue({
  el: '#app',
  data: {
    userInput: '',
    parsedInput: []
  }
})

let parse = input => {
    return input.split(',')
}

How should I go about updating data.parsedInput with the parse() function using the v-model change? What is the proper Vue way of doing this?

Upvotes: 1

Views: 6017

Answers (1)

yuriy636
yuriy636

Reputation: 11681

A proper Vue way of a data property that depends on another is with a computed property, that way parsedInput is automatically updated whenever userInput changes:

let parse = input => {
  return input.split(',')
}

new Vue({
  el: '#app',
  data: {
    userInput: '',
  },
  computed: {
    parsedInput() {
        return parse(this.userInput)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
<body>
  <div id="app">
    <input id="user-input" type="text" v-model="userInput">

    <ul id="parsed-list">
      <li v-for="item in parsedInput">
        {{ item }}
      </li>
    </ul>
  </div>
</body>

As a sidenote: declare the parse function before using it, to prevent is not defined errors.

Upvotes: 2

Related Questions