Vue.js add function to a component
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>
Rémy Kaloustian
Updated on June 15, 2022Comments
-
Rémy Kaloustian almost 2 years
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 ?
-
palaѕн over 6 yearsTrigger an event in child click method using
$emit(eventName)
and listen to an event in parent using$on(eventName)
. -
Alex over 6 yearsThis video about parent-child communication might help.
-
-
Rémy Kaloustian over 6 yearsThank you ! For me that was the first case, just calling a function from the same component. Works like a charm.