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: {
  ...mapGetters({
    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 getStudent.name to v-model as shown below.

<input type="text" v-model="getStudent.name">

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

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

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

<input ... v-model="getStudent.name || 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?

javascriptvue.js

Answers

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.$store.getters.get_student.name
    },
    set: function(val) {
      this.$store.commit('set_student_name');
    }
  }
}

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="getStudent.name" @input="update_name($event.target.value)">


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