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

Unable to load layout content from browser storage

我正在使用名为 gridstack.jslibrary。我有一个 grid 如下所示 ↓

这是我使用的代码:

<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'),
            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))
}

现在 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", 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")
    }
}

但由于某种原因我得到了这个错误

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。现在我只是想不通为什么它是未定义的。我在网上查找帮助,但没有找到任何有用的方法来解决我的问题。我在 stack overflow

上找到了这两个问题

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

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

如 'bug' 报道 https://github.com/gridstack/gridstack.js/issues/1405 中所述,他混合了 $(".grid-stack") 的旧 API 调用,这是基于 v0.6 的 jquery 代码和旧版本和最新版本 2.x 使用 GridStack.init() 初始化和 return 网格指针。

GridStack 不使用 jquery API 因为 1.x