I pass the array to child as prop. And trying to use it in google map method. But when I use it inside initMap: function the array being empty.
in parent
<div class=”mapWrap”>
<mapping :articles=”filterArticles” />
</div>
computed: {
filterArticles(){
let api = this.$store.getters.articles;
let filteredStates = api.filter((article) => {
return (this.keyword.length === 0 || article.address.includes(this.keyword)) &&
(this.regions.length === 0 || this.regions.includes(article.region)) &&
(this.rooms.length === 0 || this.rooms.includes(article.rooms1)) &&
(this.city.length === 0 || this.city.includes(article.city))
});
return filteredStates;
},
}
in child
props: {
articles: {
type:Array
},
},
name:”mapping”,
data(){
return {
marker:[],
}
},
mounted(){
this.initMap();
},
methods: {
initMap: function() {
var mapOptions = {
mapTypeId: ‘roadmap’,
center: new google.maps.LatLng(35.652832, 139.839478),
zoom: 10
};
var map = new google.maps.Map(document.getElementById(“map”), mapOptions);
var articles = this.articles;
console.log(articles);
},
},
The way when doing it wrong? Because prop has the items but when I put it inside the initMap method, it starts being empty…
Solution :
there is tried to trace the code and from what you have, it will work in most cases EXCEPT if the data that you have fetched using this.$store.getters.articles is async. Ideally, you should not be relying on the child component’s mount event because it can get mounted way before you can display any data. To verify that, you can add a console.log(this.articles) inside the mounted hook and see that it’s most likely empty.
What I suggest you do is, given that in the parent component you have articles as a computed property (which is reactive), you should also call the initMap inside the child every time the prop articles changes. The easiest way to do just that is with a watcher inside the child component:
watch: {
articles () {
this.initMap()
}
}