0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

HTMLのストレージ機能への配列の入出力でハマったこと

Last updated at Posted at 2020-05-13

sessionStorageとlocalStorageに配列を保存するときにエラーがでて嵌ったので、同じような人がいれば参考までに。

そもそも

詳細は下記をご参考ください。

sessionStorageをつかってみる
https://qiita.com/uralogical/items/ade858ccfa164d164a3b

失敗パターン

今回もVue.jsベースで話していきますが、他フレームワークでも同じです。

page1.vue
<template>
  <div>
    <div>
      <button @click="test">テスト</button>
      <ul>
        <li v-for="item in list" v-bind:key="item.id">
          {{ item.id }}/{{ item.name }} 
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
    data() {
        return {
            list:[]
        }
    },
    methods: {
        test: function() {
            const data = [
                { id: 1, name: 'test1'},
                { id: 2, name: 'test2'},
                { id: 3, name: 'test3'}
            ]
            window.sessionStorage.setItem("data", data)
            this.list = window.sessionStorage.getItem("data")
        }
    }
}
</script>

なぜ?

sessionStorageの格納情報を確認したところ、どうやら正しく情報が格納されていない様子。。。

対応方法

JSON配列に変換し使います。

page1.vue
<template>
  <div>
    <div>
      <button @click="test">テスト</button>
      <ul>
        <li v-for="item in list" v-bind:key="item.id">
          {{ item.id }}/{{ item.name }} 
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
    data() {
        return {
            list:[]
        }
    },
    methods: {
        test: function() {
            const data = [
                { id: 1, name: 'test1'},
                { id: 2, name: 'test2'},
                { id: 3, name: 'test3'}
            ]
            window.sessionStorage.setItem("data", JSON.stringify(data))
            this.list = JSON.parse(window.sessionStorage.getItem("data"))
        }
    }
}
</script>

うまくいきました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?