I'm currently working on a vue.js component that utilizes a search field to query the Google Places API (for simplicity, I've removed some details). The response from the API is a list of checkboxes representing different places. My goal is to set a flag checked
to true
on the selected object when a user checks a place.
However, I've encountered an issue where I want this property to be reactive, but it seems adding reactive properties at runtime does not work as expected (refer to https://vuejs.org/guide/reactivity.html).
<template>
<form>
<input type="text" ref="complete" v-bind:placeholder="placeholder">
<fieldset v-if="places" class="checklist">
<h4>Select your store locations:</h4>
<div v-for="place in places">
<input :id="place.id" type="checkbox" v-model="place.checked">
<label :for="place.id">
{{ place.name }}<br>
<span class="subtext">{{ place.formatted_address }}</span>
</label>
</div>
</fieldset>
</form>
</template>
<script>
export default {
data() {
return {
places: [],
api: {
domain: 'https://maps.googleapis.com/maps/api/js',
key: 'API Key',
libraries: 'places',
},
};
},
mounted() {
window.onload = this.loadScript(
`${this.api.domain}?key=${this.api.key}&libraries=${this.api.libraries}`,
this.bindAutocomplete
);
},
watch: {
},
methods: {
loadScript(src, callback) {
const script = document.createElement('script');
document.body.appendChild(script);
if (callback) {
script.onload = callback;
}
script.src = src;
},
bindAutocomplete() {
this.autocomplete = new google.maps.places.SearchBox(
this.$refs.complete
);
this.autocomplete.addListener('places_changed', this.pipeAddress);
},
pipeAddress() {
this.places = this.autocomplete.getPlaces();
},
},
};
</script>
The component seems to function properly, however, I'm unable to programmatically set any checkboxes to "checked", for example using
this.places.forEach((place) => { place.checked = true; }
. How can I achieve this in a proper manner?
Thank you,
Henning