2

I am using Vue.js and I would like to add a function to my component, Map.vue, so when I click the button it calls a function declared in the same file :

<template>
 <div>
 <div class="google-map" :id="mapName">
 </div>
 <button >Do stuff</button> 
 </div>
</template>

I have only seen examples when the function is declared in the App.vue. How do you do that in my Map.vue file ?

asked Jan 17, 2018 at 16:34
2
  • Trigger an event in child click method using $emit(eventName) and listen to an event in parent using $on(eventName). Commented Jan 17, 2018 at 16:39
  • This video about parent-child communication might help. Commented Jan 17, 2018 at 16:52

1 Answer 1

13

Events

Both App.vue and Map.vue are components so they work the same for calling functions (methods) "in the same file" (single file components).

Trigger an event by adding v-on:click="yourFunctionHere()" and then make sure to declare your function in the methods object of the script section:

Map.vue

<template>
 <div>
 <div class="google-map" :id="mapName">
 </div>
 <button v-on:click="doStuff()">Do stuff</button> 
 </div>
</template>
<script>
 export default {
 methods: {
 doStuff () {
 alert('Did something!')
 }
 }
 }
</script>

Custom Events

Since it's a little unclear what confused you about the child component Map.vue (since you understand the parent App.vue), perhaps you are asking how to call a function in App.vue from a button in the child Map.vue?

If that's the case, then you need to use custom events for child to parent communication:

Map.vue

<template>
 <div>
 <div class="google-map" :id="mapName">
 </div>
 <button v-on:click="doStuff()">Do stuff</button> 
 </div>
</template>
<script>
 export default {
 methods: {
 doStuff () {
 this.$emit('childStuff', 'some value from child')
 }
 }
 }
</script>

App.vue

<template>
 <div>
 <Map v-on:childStuff="value => { parentStuff(value) }"></Map>
 </div>
</template>
<script>
 import Map from './components/Map'
 export default {
 components: {
 Map
 },
 methods: {
 parentStuff (value) {
 alert(value)
 }
 }
 }
</script>
tony19
140k24 gold badges281 silver badges354 bronze badges
answered Jan 17, 2018 at 17:28
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! For me that was the first case, just calling a function from the same component. Works like a charm.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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