vue.js学习笔记(2)— sessionStorage存储和获取数据

效果图:css

上代码:html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>session</title>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
        <style type="text/css">
            #session {
                width: 600px;
                margin: 0 auto;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div id="session">
            <input type="text" v-on:keyup.enter="addNew()" v-model="inputValue" placeholder="请输入要保存的数据"/>
            <ul>
                <li v-for="item in items">{{ item.name }}</li>
            </ul>
        </div>
        
        <script>
            var storeKey = "studentName";
            var storage = {
                fetch:function(){
                    return JSON.parse(sessionStorage.getItem(storeKey) || "[]")
                },
                save:function(items){
                    console.log("00001");
                    sessionStorage.setItem(storeKey,JSON.stringify(items));
                }
            }
            var vm = new Vue({
                el:"#session",
                data:{
                    items:storage.fetch(),
                    inputValue:""
                },
                methods:{
                    //向数组添加内容
                    addNew:function(){
                        this.items.push({
                            name:this.inputValue
                        }),
                        this.inputValue = null
                    }
                },
                watch:{
                    //监听items的变化
                    items:{
                        handler:function(items){
                            storage.save(items);
                        },
                        deep:true
                    }
                }
            })
        </script>
    </body>
</html>

代码解读:vue

  vue实例当中的data对象中用到了读取数据的方法,可是依据vue的生命周期,data是先读取的,因此,若是把方法写到methods对象当中是会报错的,因此,我把方法写到了vue实例前的storage对象当中;而后呐,html当中keyup.enter当中的enter是事件修饰符,表明在输入完毕点击enter的时候会触发addNew()这个方法,这个方法是向空数组(items)添加数据,这当中inputValue是双向绑定的,并且为了体验度更高,enter以后把input值清空,方便下次直接输入;addNew()方法以后,虽然向数组添加了你输入的内容,可是这些内容并无添加到咱们的sessionStorage会话里面,这样的话,咱们items.fetch()是取不到值的,因此要来一个监听函数,watch.items应运而生,表明着实时监控items的变化,而后经过.save()方法向sessionStorage添加数据,添加数据的时候要转化成json字符串类型,否则会报错,而后咱们就能够在fetch()方法里面调用了chrome

相关文章
相关标签/搜索