vue.js學習筆記(2)— sessionStorage存儲和獲取數據


效果圖:

上代碼:

<!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實例當中的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()方法里面調用了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM