我的参数在单击事件后在函数中安慰或设置本地存储值方面工作得很好。但我想通过在Vue中全局传递window obj来设置它
AppStorage.storeLocation(position.coords.latitude,position.coords.longitude);
这个参数可以正常工作。app的存储是在app.js文件中全局定义的。
import AppStorage from './helpers/AppStorage';
window.AppStorage = AppStorage;
这是我的appstorage文件:
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();
为什么不工作?
您可以创建一个重写的AppStorage.js
文件,如
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 }));
从LocalStorage检索:
AppStorage.getItem("location");
您可以将store
和retrive
的localStorage
值转换为App.vue
分量,如
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>
演示链接