2
votes

I'm having trouble understanding how props work in VueJS, some help would be greatly appreciated. It is a simple google map component that I wish to show on the page and pass the id element of the div dynamically as a prop to the underlying template.

html file -

<div id="app">
    <google-map name="map"></google-map>
</div>

vue file -

<template>
    <div :id="mapName"></div>
</template>

<script>
module.exports = {
    name: 'google-map',
    props: [ 'name' ],
    data: () => {
        console.log(this.name); // ERROR: name is undefined
        return {
            mapName: this.name
        };
    },
    mounted: () => {
        const map = new google.maps.Map(document.getElementById(this.mapName), {
            zoom: 14,
            center: new google.maps.LatLng(39.305, -76.617)
        });
    }
}
</script>

<style scoped>
#map {
  width: 800px;
  height: 600px;
  margin: 0 auto;
  background: gray;
}
</style>

The error I get is that this.name is undefined inside the data() method of the component object.

1
Remove name and data altogether; and use name instead of mapName. Explanations in the introduction part of the guide.pishpish
If you wish to send name and use mapName in the child component, add a computed property: computed: { mapName: () => this.name }.pishpish

1 Answers

15
votes

the reason that console.log(this.name); returns undefined is you are using Arrow function. It should be

data: function() {
    // ...
},

mounted: function() {
    // ...
}

or

data() {
    // ...
},

mounted() {
    // ...
}

Explanation:

See https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

enter image description here