vue深度監控數據改變,緩存數據到本地


項目效果圖:

var vm = new Vue({
        el:'#app',
        data:{
            students:[],
        },
        watch:{
            students:{
                handler(){
                    localStorage.setItem('student',JSON.stringify(this.students))
                },
                deep:true,
            }
        },
        created(){
            this.students = JSON.parse(localStorage.getItem('student')) || []
        }
    })

需要注意兩個地方:

需要用JSON.stringify()轉換為字符串存儲起來,再用JSON.parse()轉換為對象
首次進入緩存中沒數據的時候會報錯,需要賦值為空數組 || []

 


免責聲明!

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



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