无法从浏览器存储中加载布局内容

问题描述

我正在使用一个名为{strong> gridstack.js 的library我有一个grid,看起来像下面的↓

image

这是我使用的代码

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gridstack@2.0.0/dist/gridstack.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
<script src="https://cdn.jsdelivr.net/npm/gridstack@2.0.0/dist/gridstack.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

<style>

.card-body {
    -webkit-Box-flex: 1;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    min-height: 1px;
    padding: 1.25rem;
}

.newWidget {
    background-color: #6cad84 !important;
}
.card {
    background: none;
}

#trash {
    background-color: #cc6857;
}
.text-white {
    color: #fff !important;
}
.text-center {
    text-align: center !important;
}

    
.ui-resizable-se,.ui-resizable-sw {
    opacity: 0 !important;
}

.ui-resizable-se {
    bottom: -5px !important;
    right: -5px !important;
}


.grid-stack-item-content{
    overflow:hidden !important
}

    

</style>


<body>


<div class="container-fluid">
    <span id="dashboardName">
        <p>My dashboard</p>
    </span>

    <div class="row">


        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 "> 

            <!-- gridstack.js elements go here -->
            <div class="grid-stack">
               

             <div class="grid-stack-item ui-draggable-handle ui-resizable" data-gs-x="0" data-gs-y="3" data-gs-width="7" data-gs-height="4">
                    <div class="grid-stack-item-content ui-draggable-handle card-color card-body cardProperty">
                        <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">

                    </div>
              </div>


              <div class="grid-stack-item ui-draggable-handle ui-resizable hasPanelHeader " data-gs-x="8" data-gs-y="6" data-gs-width="5" data-gs-height="4">
              
                <div class="grid-stack-item-content ui-draggable-handle  panel-warning  card-body cardProperty">
                            
                            <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">
                </div>
            </div>

             


              <div class="grid-stack-item ui-draggable-handle ui-resizable" data-gs-x="0" data-gs-y="6" data-gs-width="4" data-gs-height="4">
                    
                    <div class="grid-stack-item-content card-body ui-draggable-handle card-color cardProperty">
                        
                        <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">

                    </div>
             </div>


             <div class="grid-stack-item ui-draggable-handle ui-resizable hasPanelHeader " data-gs-x="4" data-gs-y="6" data-gs-width="4" data-gs-height="4">
              
                <div class="grid-stack-item-content ui-draggable-handle  panel-warning  card-body cardProperty">
                            
                            <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80"> 
                </div>
            </div>

            </div>

        </div>

     </div> 
</div>


<script type="text/javascript">

// save the size and coordinates of the widgets
function saveData() {
    var items = [];

    $('.grid-stack-item.ui-draggable').each(function () {
        var $this = $(this);
        items.push({
            x: $this.attr('data-gs-x'),y: $this.attr('data-gs-y'),w: $this.attr('data-gs-width'),h: $this.attr('data-gs-height'),content: $('.grid-stack-item-content',$this).html()
        });
    });

    // Save data to local storage
    localStorage.setItem("grid-layout",JSON.stringify(items))
}


// check for widgets size and coordinates and add to the grid
function getWidgetData() {

    let serialization = null;
    let grid_stack = $('.grid-stack');
    let grid = $('.grid-stack').data('gridstack')
    console.log("grid",grid)

    if (localStorage.getItem("grid-layout") !== null) {

        serialization = JSON.parse(localStorage.getItem("grid-layout"));

        _.each(JSON.parse(serialization),function (node) {
            grid.addWidget($('<div><div class="grid-stack-item-content"> </div></div>'),node.x,node.y,node.w,node.h);
        });

       
    } else {
        console.log("There was no local storage data to read")
    }
}


// check for localstorage in the beginning
getWidgetData ()

var simpleGrid = GridStack.init({
      alwaysShowResizeHandle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator
        .userAgent),resizable: {
        handles: 'e,se,s,sw,w,n'
      },animate: true,acceptWidgets: true,dragIn: '.newWidget',// class that can be dragged from outside
      draginoptions: { revert: 'invalid',scroll: false,appendTo: 'body',helper: 'clone' },removable: '#trash',// drag-out delete class
      removeTimeout: 100,});

// save the widgets layout on every change
simpleGrid.on('added removed change',function(e,items) {
    saveData()
});

</script>

</body>

现在grid看起来不错,我可以resizedrag widgets了。现在,我想store在浏览器存储中进行更改,并在页面加载时将其检索。因此,如上面的代码中所述,这就是我对store布局所做的

// save the size and coordinates of the widgets
function saveData() {
    var items = [];

    $('.grid-stack-item.ui-draggable').each(function () {
        var $this = $(this);
        items.push({
            x: $this.attr('data-gs-x'),JSON.stringify(items))
}

现在load来自浏览器存储的布局,这就是我要做的(在上面的代码中提到)

// check for widgets size and coordinates and add to the grid
function getWidgetData() {

    let serialization = null;
    let grid_stack = $('.grid-stack');
    let grid = $('.grid-stack').data('gridstack')
    console.log("grid",node.h);
        });


    } else {
        console.log("There was no local storage data to read")
    }
}

但是由于某些原因,我会收到此错误

index.html:156 Uncaught TypeError: Cannot read property 'addWidget' of undefined
    at index.html:156
    at r (lodash.min.js:9)
    at Function.hf (lodash.min.js:83)
    at getWidgetData (index.html:155)
    at index.html:168

在下面显示这段代码

 let grid = $('.grid-stack').data('gridstack')

由于某些原因,它给出了 undefined 。现在我无法弄清楚为什么它是未定义的。我在网上寻找帮助,但没有找到能解决我问题的有用信息。我在堆栈溢出时发现了这两个问题

Gridstack undefined when calling $(".grid-stack").data("gridstack") in global context

can't read property addWidget of undefined with JSON and gridstack

但是我不太了解他们在做什么,或者是否适用于我的情况。我在做什么错了?

解决方法

如报告https://github.com/gridstack/gridstack.js/issues/1405的“错误”中所述,他混用了$(".grid-stack")的旧API调用,该API是基于v0.6及更低版本的jquery代码,而最新版本是使用{{ 1}}初始化并返回网格指针。

GridStack从1.x开始不使用jquery API