Reputation: 1059
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.
Upvotes: 2
Views: 4672
Reputation: 20845
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://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks
Upvotes: 17