vue.js – Computed Properties – Using computed setters for v-model


You might need a v-model on a computed property. Normally, the v-model won’t update the computed property value.

The template:

<div id="demo">
  <div class='inline-block card'>
    <div :class='{onlineMarker: true, online: status, offline: !status}'></div>  
    <p class='user-state'>User is {{ (status) ? 'online' : 'offline' }}</p>
  </div>

  <div class='margin-5'>
    <input type='checkbox' v-model='status'>Toggle status (This will show you as offline to others)
  </div>
</div>

Styling:

#demo {
  font-family: Helvetica;
  font-size: 12px;
}
.inline-block > * {
  display: inline-block;
}
.card {
  background: #ddd;
  padding:2px 10px;
  border-radius: 3px;
}
.onlineMarker {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  transition: all 0.5s ease-out;
}

.online {
  background-color: #3C3;
}

.offline {
  background-color: #aaa;
}

.user-state {
  text-transform: uppercase;
  letter-spacing: 1px;
}

.margin-5 {
  margin: 5px;
}

The component:

var demo = new Vue({
    el: '#demo',
    data: {
        statusProxy: null
    },
    computed: {
        status: {
            get () {
                return (this.statusProxy === null) ? true : this.statusProxy     
            }
        }
    }
})

fiddle
Here you would see, clicking the radio button has no use at all, your status is still online.

var demo = new Vue({
    el: '#demo',
    data: {
        statusProxy: null
    },
    computed: {
        status: {
            get () {
                return (this.statusProxy === null) ? true : this.statusProxy     
            },
            set (val) {
                this.statusProxy = val            
            }
        }
    }
})

fiddle
And now you can see the toggle happens as the checkbox is checked/unchecked.

if you want to reproduce, please indicate the source:
vue.js – Computed Properties – Using computed setters for v-model - CodeDay