首页 >社区问答列表 >javascript - vue localStorages相关 路由传值页面刷新后报错

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",
                 以下省略...
            }
        ]
    }
}

  • 仅有的幸福
  • 仅有的幸福    2017-07-05 10:57:501楼

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

    1. 先把mounted全部注释

    2. 看看会不会报错

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

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

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

    +0添加回复

  • 回复