Vuejs - Assign computed properties to data()

bruh Source

I have an input field that I would like to either be blank or populate depending on the condition

  • Condition A: new student, blank field
  • Condition B: existing student, populated field

This data is coming from the data() function or a computed: property. For example:

data () {
  return {
    studentName: '', // empty student name property (/new student route)
    studentPersonality: ''
computed: {
    getStudent // existing student object (/edit student route)

My input field should either be blank if we are arriving from the /new student route, or populate the field with the existing student info, if we're coming from the /edit route.

I can populate the input field by assigning to v-model as shown below.

<input type="text" v-model="">

...and of course clear the field by instead assigning studentName to v-model

<input ... v-model="studentName">

Challenge: How can I use IF it exists, but fall back on the blank studentName data() property if does NOT exist? I have tried:

<input ... v-model=" || studentName">

...which seemed to work, but apparently invalid and caused console errors

'v-model' directives require the attribute value which is valid as LHS

What am I doing wrong?



answered 8 months ago m3characters #1

There's really no need to have the input field register to different properties in your vue component.

If you want to have a computed property that is also settable, you can define it using a set & get method.

computed: {
  student_name: {
    get: function() {
      return this.$
    set: function(val) {

One other way is to separate the value from the input change handler in the input element itself, in this case you would use the getter as you've set it

<input type="text" :value="" @input="update_name($">

And lastly, if you need to really use two different properties you can set them on a created/activated hook (and answering your original question):

created: function() {
  this.studentName = this.getStudent
activated: function() {
  this.studentName = this.getStudent

You'll always need to delegate the update to the store though so I would either go with the get/set computed property, or the value/update separation

comments powered by Disqus