Vue.js Using Computed For v-model Form Input

Dec 26, 2017
Use Computed Setter to Format and Convert v-model data

I have a websites property which is an array, which I wanted to format as newline in textarea, and convert textarea back to array when stored as websites property.

The solution is to use Computed Setter.

<template>
  <form>
    <input name="name" v-model="item.name">
    <textarea name="websites" v-model="websites"></textarea>
  </form>
</template>

<script>
export default {
  data() {
    return {
      item: {
        name: 'Test',
        websites: ['https://code.luasoftware.com/', 'https://www.google.com']
      }
    }
  },
  computed: {
    websites: {
      get() {
        return this.item.websites.join('\n')
      },
      set(value) {
        this.item.websites = value.split('\n')
      }
    }
  },  
}
</script>

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.