Mi argumento funciona bien para consolar o establecer el valor de almacenamiento local en la función después del evento de clic. Pero quiero configurarlo pasándolo en window obj globalmente en Vue.
AppStorage.storeLocation(position.coords.latitude,position.coords.longitude);Este argumento funciona bien. Y el almacenamiento de la aplicación se define globalmente en el archivo app.js.
import AppStorage from './helpers/AppStorage'; window.AppStorage = AppStorage;Este es mi archivo de almacenamiento de aplicaciones:
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();¿Por qué no funciona?
Puede crear y reescribir el archivo AppStorage.js como
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();Guardar en almacenamiento local:
AppStorage.setItem("location",JSON.stringify({ latitude: position.coords.latitude, longitude: position.coords.longitude }));Recuperar de LocalStorage:
AppStorage.getItem("location"); Puede store y localStorage valores de App.vue retrive ,
Código fuente completo del componente app.vue
<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>