[Vuejs]-How to listen to events emitted by nested components I do not control?

0👍

You can extend the v-select component to take a bus prop, onto which you can relay the update:searchInput event, so that you can catch it at the top level.

Vue.component('my-select', {
  extends: Vue.component('v-select'),
  props: ['bus'],
  created() {
    this.$on('update:searchInput', (payload) => this.bus.$emit('update:searchInput', payload));
  }
});

new Vue({
  el: '#app',
  data() {
    return {
      a1: null,
      states: [
        'Alabama', 'Alaska', 'American Samoa', 'Arizona',
        'Arkansas', 'California', 'Colorado', 'Connecticut',
        'Delaware', 'District of Columbia', 'Federated States of Micronesia',
        'Florida', 'Georgia', 'Guam', 'Hawaii', 'Idaho',
        'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky',
        'Louisiana', 'Maine', 'Marshall Islands', 'Maryland',
        'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi',
        'Missouri', 'Montana', 'Nebraska', 'Nevada',
        'New Hampshire', 'New Jersey', 'New Mexico', 'New York',
        'North Carolina', 'North Dakota', 'Northern Mariana Islands', 'Ohio',
        'Oklahoma', 'Oregon', 'Palau', 'Pennsylvania', 'Puerto Rico',
        'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee',
        'Texas', 'Utah', 'Vermont', 'Virgin Island', 'Virginia',
        'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
      ],
      bus: new Vue()
    }
  },
  created() {
    this.bus.$on('update:searchInput', (payload) => console.log("Got", payload));
  }
})
<link href="https://unpkg.com/vuetify@0.17.6/dist/vuetify.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify@0.17.6/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-card color="grey lighten-4" flat>
      <v-card-text>
        <v-container fluid>
          <v-layout row wrap>
            <v-flex xs12 sm6>
              <v-subheader v-text="'Autocomplete'"></v-subheader>
            </v-flex>
            <v-flex xs12 sm6>
              <my-select :bus="bus" v-bind:items="states" v-model="a1" label="Select" autocomplete></my-select>
            </v-flex>
          </v-layout>
        </v-container>
      </v-card-text>
    </v-card>
  </v-app>
</div>
👤Roy J

Leave a comment