External events in custom component

So, I created my custom single-file component with select based on choices.js plugin.

<template>
  <select
     {{#if $props.name}}name="{{$props.name}}"{{/if}}
     id="{{#if $props.id}}{{$props.id}}{{/if}}"
     ></select>
</template>

    <script>
      export default {
        data: function () {
          return {
            value: 'Sampletext',
            choices: [
              {
                id: 1,
                label: 'All activities',
                value: 'All activities'
              },
            ],
          }
        },
        methods: {
          createSelect (choices) {
              const elementSelect = document.querySelector('#' + this.$props['id']);
              const choicesSelect = new Choices(elementSelect, {
                choices: choices,
              });
            }
        },
        created () {
          this.createSelect(this.choices);
        }
     }
    </script>

This plugin has it’s custom events, here’s the fragment from the plugin’s documentation:
“Events fired by Choices behave the same as standard events. Each event is triggered on the element passed to Choices (accessible via this.passedElement) . Arguments are accessible within the event.detail object.”

Of course I can use standard ‘document.addEventListener’, but maybe there is some Framework7’s way to use those events properly? Thank you.

If these events are usual DOM events, then you can attach listeners as usual. For example if it has someevent event then:

<template>
  <select @someevent="onSomeEvent"
     {{#if $props.name}}name="{{$props.name}}"{{/if}}
     id="{{#if $props.id}}{{$props.id}}{{/if}}"
     ></select>
</template>

    <script>
      export default {
        data: function () {
          return {
            value: 'Sampletext',
            choices: [
              {
                id: 1,
                label: 'All activities',
                value: 'All activities'
              },
            ],
          }
        },
        methods: {
          onSomeEvent(event) {
            // do something
          },
          createSelect (choices) {
              const elementSelect = document.querySelector('#' + this.$props['id']);
              const choicesSelect = new Choices(elementSelect, {
                choices: choices,
              });
            }
        },
        created () {
          this.createSelect(this.choices);
        }
     }
    </script>

Thank you, I already solved my problem by attaching event listener to the element:

$$('#' + this.$props['id']).on('choice', function() {
  console.log('Sample select event');
});

It’s not a standard DOM event, would it work like in the example you provided?

But this is still DOM event, so you can still use @choice

1 Like