首頁  >  問答  >  主體

javascript - vue localStorages相關 路由傳值頁面刷新後報錯

程式碼相關:

剛開始學習vue的菜雞一隻,js基礎不是太好,有什麼不對的地方儘管批評指出謝謝。

productList頁面進行跳轉,然後根據index值取本地json數組中的資料來展現不同的頁面資料,點擊跳轉後沒什麼問題,然後刷新之後取不到值了,提示

[Vue warn]: Error in data(): "SyntaxError: Unexpected token u in JSON at position 0"

搜了錯誤訊息的解釋但是還是不太理解,我是按慕課的一個vue的基礎教學裡面保存localStorages的方法來的,是哪裡寫錯了嗎?

 <li v-for="(item,index) in filterList" >
    <router-link :to="{ name: 'detail', params: { id: index }}">
    </router-link>
</li>
//store.js
const STORAGE_KEY = 'epmobile'
export default {
    fetch() {
        return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
    },
    save(items) {
        window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
    }
}
//detail 页面
<script>
import Store from '../store/store'
export default {
    data() {
        return {
            articleList: '',
            index: Store.fetch()
        }
    },
    mounted() {
        this.$nextTick(function () {
            this.index = this.$route.params.id
            this.get_articleList()
        })
    },
    watch: {
       index: {
           handler: function (index) {
            Store.save()
           },
           deep: true
       }
    },
    methods: {
        get_articleList: function () {
            this.$http.get('/api/article.json').then(response => {
                let res = response.data
                if (res.status == 0) {
                    this.articleList = res.result.articleList[this.index]
                }
            })
        }
    }
}
</script>
{
    "status": 0,
    "result": {
        "articleList": [
            {
                "title": "111",
                "productImg": "/static/images/product_e/01.jpg",
                "productText": "xxxxx",
                "companyInfo": {
                    "name": "xxxx",
                    "url": "xxxxx",
                    "boothNumber": "xxxx"
                }
            },
            {
                "title": "2222222222",
                 以下省略...
            }
        ]
    }
}
ringa_leeringa_lee2663 天前955

全部回覆(1)我來回復

  • 仅有的幸福

    仅有的幸福2017-07-05 10:57:50

    大機率是json格式錯誤
    首先你去判斷一下錯誤出在哪裡

    1. 先把mounted全部註解

    2. 看看會不會報錯

    3. 然後一條一條的加進去

    localStorage的值如果你使用的chrome,打開f12在application那裡就能看到

    大概率出現的原因是,你在一json格式保存數據之前先獲取了一個非json數據,然後json.parse就報錯了

    回覆
    0
  • 取消回覆