首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >继续在混合应用Javascript中获取[Object Object]

继续在混合应用Javascript中获取[Object Object]
EN

Stack Overflow用户
提问于 2019-09-24 23:33:25
回答 1查看 128关注 0票数 0

我正在使用Nuxt JS、Cordova和Cordova Native Storage (本质上是本地存储)构建一个混合应用程序。

我正在将一个对象保存到本机存储中,并在mounted()中的页面加载时检索它。然而,无论我如何尝试访问对象数据,我都会收到以下错误:

[Object Object]

在每个页面上加载的组件中,我的JS是:

代码语言:javascript
运行
复制
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的对象如下所示:

代码语言:javascript
运行
复制
export const state = () => ({
  pageTitle: 'App name',
  dataUrls: [],
  intervalData: [],
  settings: [],
  experimentalFeatures: [],
  customAlertSeen: false,
  user: null,
  account: null,
  payloadOutput: null
})

每次运行getItem时,alert(parseObj)始终返回[Object Object] rather than for instance, the data. And if I try returningparseObj.localStorage.pageTitlewhich is clearly defined instore/localStorage.jsit returnsundefined`

我在哪里做错了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-24 23:40:05

所以,localStorage存储的是字符串,而不是对象。

将项目保存到localStorage时,首先将其转换为字符串,然后在检索时从字符串中解析它。

代码语言:javascript
运行
复制
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"}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58083732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档