我正在使用 Nuxt JS、Cordova 和 Cordova Native Storage(本质上是本地存储)构建一个混合应用程序。
我正在将一个对象保存到 native 存储中,并在 mounted()
内的页面加载时检索它,但是,无论我尝试如何访问对象数据,我都会不断收到以下错误:
[对象对象]
我在每个页面加载的组件中的JS是:
import { mapState } from 'vuex';
export default {
mounted () {
document.addEventListener("deviceready", this.getNativeStorage(), false)
},
methods: {
getNativeStorage() {
window.NativeStorage.getItem("beacon_native_storage", (value) => {
var parseObj = JSON.parse(value)
alert(parseObj)
alert(parseObj.localStorage)
}, (error) => {
alert(`Error: ${error.code}-${error.exception}`)
});
},
refreshNativeStorage(currentState) {
window.NativeStorage.initWithSuiteName("beacon");
window.NativeStorage.setItem("beacon_native_storage", JSON.stringify(currentState), () => {
alert('Stored currentState')
}, (error) => {
alert(`Error: ${error.code}`)
});
}
},
computed: {
state () {
return this.$store.state
}
},
watch: {
state: {
handler: function (val, Oldval) {
setTimeout(function () {
this.refreshNativeStorage(this.state)
}.bind(this), 10)
},
deep: true
}
}
}
Vuex 中的对象如下所示:
export const state = () => ({
pageTitle: 'App name',
dataUrls: [],
intervalData: [],
settings: [],
experimentalFeatures: [],
customAlertSeen: false,
user: null,
account: null,
payloadOutput: null
})
每次 getItem
运行时,alert(parseObj)
总是返回 [Object Object],而不是数据等。如果我尝试返回
parseObj.localStorage.pageTitle ,它在
store/localStorage.js 中明确定义,它会返回
undefined`
我哪里出错了?
最佳答案
所以,发生的情况是 localStorage 存储字符串,而不是对象。
将项目保存到 localStorage 时,首先将其转换为字符串,然后在检索时从字符串中解析它。
localStorage.setItem('a', {b:'c',d:'e'})
localStorage.getItem('a') // "[object Object]" <- note the quotes!
localStorage.setItem('a', JSON.stringify({b:'c',d:'e'}))
JSON.parse(localStorage.getItem('a')) // {b: "c", d: "e"}
关于javascript - 继续在混合应用程序 Javascript 中获取 [Object Object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083732/