1

I'm trying to emit something from within my VueJS component to a function which sits in the html page containing the component. Am I missing something, or is this not possible?

Within my component as a method:

insert: function(){
    this.$emit('insertItem', 123);
}

In the page containing the component:

<medialibrary @insertItem="insertItem(arg);"></medialibrary>


<script>
    function insertItem(arg){
        console.log('insertItem');
        console.log(arg);
    }
</script>
3
  • In case the other component also is a Vue instance, you could use a global event bus Commented May 3, 2017 at 8:47
  • This is just one component (medialibrary) and I want to emit an event with a parameter to some Javascript which is in the HTML page outside of the VueJS instance. Commented May 3, 2017 at 9:00
  • Just call this global function from event intermediate event listener. Commented May 3, 2017 at 9:05

1 Answer 1

5

This is actually more possible than it seems at first look. If the function is global (in particular, visible to the parent Vue), it can be called by the Vue even if it is not a method of the Vue. (It would arguably be a better idea to create a method that calls the global function.)

The main difficulty with your code was camelCasing where it should be kebab-case.

If you want insertItem to get the arg from the $emit, the HTML should only give the function name, and Vue will take care of passing the args:

<medialibrary id="app" @insert-item="insertItem"></medialibrary>

My snippet uses your original code, which provides arg from the parent Vue.

function insertItem(arg) {
  console.log('insertItem');
  console.log(arg);
}

new Vue({
  el: '#app',
  data: {
    arg: 'hi there'
  },
  components: {
    medialibrary: {
      template: '<div><button @click="insert">Insert</button></div>',
      methods: {
        insert() {
          console.log("Emit");
          this.$emit('insert-item', 123);
        }
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.2/vue.min.js"></script>
<medialibrary id="app" @insert-item="insertItem(arg);"></medialibrary>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, know it would be something silly like the prop name :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.