0👍
✅
when you just set it inside the function, it becomes a local variable. To set it as a global variable, you need to overwrite(and define) it as a window
property:
export default defineComponent({
name: "Map",
components: {},
setup() {
// Array contains html ID names corresponding to each div containing a map (SVG)
const MAP_DIVS = document.getElementsByClassName("map");
// Init vars to keep track of the actively displayed div (SVG) and corresponding map data
window.activeMap = null;//window property, undefined if this line is left out
onMounted(() => {
checkMap();
});
// Define function to print activeMap every second
function checkMap() {
console.log(window.activeMap);//access is possible as activeMap too, but its safer to use the window property
setTimeout(checkMap, 1000);
}
// Define function to create toggle map btns
function createToggleBtn(parentDiv, divControlled, btnText, toggleFunc) {
var btn = document.createElement("button");
btn.classList.add("toggle_btn");
btn.innerText = btnText;
btn.value = divControlled;
btn.onclick = function () {
toggleFunc(divControlled);
};
document.getElementById(parentDiv).appendChild(btn);
return btn;
}
// Define toggle map functionality--used to change the 'active' map div/SVG that's displayed
function toggleMap(divName) {
if (divName == MAP_DIVS[0].id && activeMap != MAP_DIVS[0].id) {
window.activeMap = MAP_DIVS[0].id;//Here it is important to define it as a window property
} else if (divName == MAP_DIVS[1].id && activeMap != MAP_DIVS[1].id) {
window.activeMap = MAP_DIVS[1].id;//here too
} else if (divName == MAP_DIVS[2].id && activeMap != MAP_DIVS[2].id) {
window.activeMap = MAP_DIVS[2].id;//and also here
}
}
return {
checkMap,
toggleMap,
createToggleBtn,
};
},
});
Source:stackexchange.com