Possible to detect q-select options change?



  • I have cascading selects, where the options for each subsequent select is dependent on the selects that have been selected before it. Here is an example of the first two (there are like 9 of these things in the full application), where the options for the second select are sourced by a computed property that uses the selected value of the first select. Works great!

    <template lang="pug">
        .q-gutter-md
            q-select(v-model="model.a", :options="computedOptionsA", emit-value, map-options)
            q-select(v-model="model.b", :options="computedOptionsB", emit-value, map-options)
    </template>
    
    <script>
    export default {
        computed: {
            computedOptionsA () {
                return options.a
            },
            computedOptionsB () {
                const result = options.b.filter(o => matchFilterKey(o.filterKey, this.model, 1))
                if(result.length === 1) { this.model.b = result[0].value}  // <- this smells!
                return result
            }
        }
    }
    </script>
    

    However, one of the things I would like to do, is automatically select the option if there is only a single option to be selected. The commented line in computedOptionsB works just fine, but it discouraged since it introduces a computed method side effect.

    Is there a better way to do this?

    If I could detect that the options changed, I imagine I could do it there, but the closest I can find is the “add” and “remove” events, but they only seem to respond to the usage of their similarly-named methods.

    Thanks in advance for any recommendations!



  • @haigha-earwicket which option you want to detect, options.b? you can set a watcher for it, but seeing as you didn’t mutate it (const result = options.b.filter(o => matchFilterKey(o.filterKey, this.model, 1))), won’t react to it. you could make result a component data tho and watch that one.



  • @metalsadman If anything, I would need to watch the result of computedOptionsB. If I were to make result into component data, then I would just be swapping out one side-effect for another.



  • @metalsadman ok, I had no idea you could set a watcher on a computed property!

      watch: {
        'computedOptionsB': function (value) {
          if (value.length === 1) { this.model.b = value[0].value }
        }
      }
    

    and this allowed me to return my computed property to a no-side effects mode:

        computedOptionsB() {
          return options.b.filter(o => matchFilterKey(o.filterKey, this.model, 1))
        },
    
    

    Thanks!


Log in to reply