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

相關文章
相關標籤/搜索