Search code examples
javascriptvuejs2vue-componentvuex

how to make custom $option extends computed or methods functionality vue


When I am building a component, some times, computed properties are getting very large and hard to read.
For example, when I have a component that handles a form with 10 fields (inputs, selects etc) I usually create 10 computed properties that checks the validation of the correspond form-field. 10 computed properties that watches for changes through v-models and so on.

What I want is if anyone know a way to create a custom property and extend the computed functionality
For example:

<template>
   <div>
       <input class="form-control" v-model="$options.vmodels.firstName">
   </div>
</template>

and the script part

export default {
   name: 'ComponentA',  
   computed: {},
   vmodels: {
      firstName:{
        get(){ return store.state.firstName}, // lets assume this works
        set(value){store.state.firstName = value}
     }
   },
   methods: {},
   watch: {},
}

I tried to use $options to call custom properties but it doesn't seem to work for computed functionallity.
For example if I want to create a computed custom property with get/set and pass it to v-model then it will never mutate to fire the set or get method.

The main reason I want that is to increase code readability. And yes I know many of you should say that I should create more than one components if the component gets very big but still I want to know if the above approach can work

Thanks in advance!


Solution

  • What I understand is that you would like to inherit some properties to use in your ComponentA. This is the exactly usage of Vue Mixins. You can create another file for your mixin for the fields of your form with computed properties as you have been using, and add that mixin in your ComponentA.