Reputation: 734
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>
Upvotes: 1
Views: 3646
Reputation: 43899
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>
Upvotes: 5