Store the array of div components after dragging

In the previous blog, the drag and drop between modules was realized, but once you refresh the page, it returns to the original appearance, which is definitely not possible. Since you have dragged it, you must want to open it next time or should I drag it After moving.

In this case we make a local storage

We use localStorage. After closing the page with sessionStorage, the data will be lost. With localStorage, the data will not be lost and will always exist on this computer until you manually clear the cache yourself (because I did not write the clear button and event on the front page).

 Add an end event to be executed after the drag is completed

    onEnd() {
      // 拖动完成之后,数组变化,就可以存入本地
      // localStorage.setItem("dragList", this.contentItems);
      localStorage.setItem("dragList", JSON.stringify(this.contentItems));
    },

After dragging, the array will definitely change (if the array is not adjusted), use localStorage.setItem("dragList", JSON.stringify(this.contentItems)); to save it locally.

Press F12 to see what you saved

Then just take

    getdragList() {
      var dragListData = localStorage.getItem("dragList");
      dragListData = JSON.parse(dragListData);
      if (dragListData) {
        var arr = [];
        arr.push(dragListData);
        this.contentItems = arr[0];
        this.contentItems.forEach((item) => {
          item.value = item.lable;
        });
        console.log("this.contentItems", this.contentItems);
      } else {
        this.contentItems = this.contentItems;
      }
    },

 This is the method to take, and it is called every time the page is opened.

  created() {
    this.getdragList();
  },

In this way, the div box can basically be dragged and stored locally.

I encountered some small problems, for example, when I got it, I did a traversal, the reason is this, because value is a component when defining the array in the previous article, so it is not what we want when it is stored up,

So for the original array contentItems I made a change

      contentItems: [
        { lable: "indexCard1", value: indexCard1 },
        { lable: "indexCard2", value: indexCard2 },
        { lable: "indexCard3", value: indexCard3 },
        { lable: "indexCard4", value: indexCard4 },
        { lable: "indexCard5", value: indexCard5 },
        { lable: "indexCard6", value: indexCard6 },
        { lable: "indexCard7", value: indexCard7 },
        { lable: "indexCard8", value: indexCard8 },
      ],

I used the component name, so that when I get the data, I reassign the value, and I still get the component.

It also found a problem

That is, the printed array will be an object when you print its data type~ This is no problem~

Guess you like

Origin blog.csdn.net/weixin_47194802/article/details/129811765