My argument works fine in consoling or setting the local storage value in the function after click event. But I want to set it by passing it on window obj globally in Vue.
AppStorage.storeLocation(position.coords.latitude,position.coords.longitude);
This argument works fine. And the app storage is defined globally in app.js file.
import AppStorage from './helpers/AppStorage';
window.AppStorage = AppStorage;
This is my appstorage file:
class AppStorage{
storeLat(lat){
localStorage.setItem('lattitude',lat);
}
storeLong(long){
localStorage.setItem('longitude',long);
}
storeLocation(lat,long){
this.storeLat(lat);
this.storeLong(long);
}
}
export default AppStorage = new AppStorage();
Why it's not working?
You can create an rewrite the AppStorage.js file like
class AppStorage {
setItem(name, content) {
if (!name) return;
if (typeof content !== "string") {
content = JSON.stringify(content);
}
return localStorage.setItem(name, content);
}
getItem(name) {
if (!name) return;
const localValues = localStorage.getItem(name);
if (typeof localValues === "string") {
return JSON.parse(localValues);
} else {
return localValues;
}
}
}
export default AppStorage = new AppStorage();
Save to LocalStorage:
AppStorage.setItem("location",JSON.stringify({ latitude: position.coords.latitude, longitude: position.coords.longitude }));
Retrive from LocalStorage:
AppStorage.getItem("location");
You can store and retrive localStorage values to App.vue component like,
Complete source code of app.vue component
<template>
<div id="app">
<p>LocalStorage Latitude: {{ location.latitude }}</p>
<p>LocalStorage Latitude: {{ location.longitude }}</p>
</div>
</template>
<script>
import AppStorage from "./helpers/AppStorage";
export default {
name: "App",
data() {
return {
location: {},
};
},
created() {
this.loadGeolocation();
},
methods: {
async loadGeolocation() {
await navigator.geolocation.getCurrentPosition((position) => {
if (position) {
console.log("position", position.coords);
AppStorage.setItem(
"location",
JSON.stringify({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
})
);
this.loadFromLocalStorage();
}
});
},
loadFromLocalStorage() {
this.location = AppStorage.getItem("location");
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>