我使用的是Vue 3和Google Maps js API.
我的目标是点击一个标记,这会打开一个信息窗口,在那个窗口中有一个按钮,用户可以点击它来运行一些代码.
我制作了一个定制的HTML元素,使其位于单击标记时创建的Infowindow中.但是我不能在这个定制的html中引用我的函数.
如何在定制的html中引用我的函数?
<script setup>
/* eslint-disable no-undef */
import { computed, ref, onMounted, onUnmounted, watch, reactive, toRaw } from 'vue'
import { useMapStore } from '../pinia/map'
import { Loader } from '@googlemaps/js-api-loader'
const mapStore = useMapStore()
//~~ MAPPING ~ load API
const GOOGLE_MAPS_API_KEY = import.meta.env.VITE_GAPI
const loader = new Loader({
apiKey: GOOGLE_MAPS_API_KEY,
version: 'beta',
libraries: ['marker']
})
const mapDiv = ref(null) // define divref to populate the map
let map = mapStore.map // get map from pinia store to persist map
const initMap = async () => {
await loader.load()
map = new google.maps.Map(mapDiv.value, {
center: { lat: 40, lng: -80 },
zoom: 4,
maxZoom: 19,
minZoom: 3
})
// create a new marker with custom content for the info window
const marker = new google.maps.Marker({
position: { lat: 40, lng: -80 },
map: map,
title: 'My Marker'
})
// create a new info window with custom HTML content
const infoWindowContent = '<div><h3>My Marker Info Window</h3><button onclick="testFx()" >WORK</button></div>'
const infoWindow = new google.maps.InfoWindow({
content: infoWindowContent
})
// add an event listener to open the info window when the marker is clicked
marker.addListener('click', () => {
infoWindow.open(map, marker)
})
}
//~ initialize map
onMounted(async () => {
await initMap()
})
const testFx = () =>{
console.log('something worked');
}
</script>
<template>
<div style="overflow-y: hidden">
<div ref="mapDiv" style="background-color: #4CAF50; width: 100%; height: 90vh"></div>
</div>
</template>
除了运行函数之外,这段代码还可以执行我需要的所有操作.我得到了这个错误:
Uncaught ReferenceError: testFx is not defined
at HTMLButtonElement.onclick