Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js add function to a component

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 ?


1 Answers

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>
like image 174
prograhammer Avatar answered Dec 08 '25 02:12

prograhammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!