javascript - vue localStorages相关 路由传值页面刷新后报错

查看:460
本文介绍了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",
                 以下省略...
            }
        ]
    }
}

解决方案

大概率是json格式错误
首先你去判断一下错误出在哪里

  1. 先把mounted全部注释

  2. 看看会不会报错

  3. 然后一条一条的加进去

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

大概率出现的原因是,你在一json格式保存数据之前先获取了一个非json数据,然后json.parse就报错了

这篇关于javascript - vue localStorages相关 路由传值页面刷新后报错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆