The front end implements dynamic dom sorting (using css properties)

The order attribute of the flex layout can set the visual order of the DOM elements to be different from the actual order, so that the dom can be sorted out of order.
Source code (vue2)

<template>
  <div>
    <div style="text-align: center">
      <input v-model="sort" /> <button @click="getsort">排序</button>
    </div>
    <div class="content">
      <div
        v-for="(item, index) in 8"
        :key="index"
        :style="{ order: getorder(index) }"
      >
        第{
   
   { index + 1 }}个div
      </div>
    </div>
  </div>
</template>
<script>
export default {
      
      
  name: "test",
  data() {
      
      
    return {
      
      
      sort: "1,2,3,4,5,6,7,8",
      arr_sort: [],
    };
  },
  methods: {
      
      
    getsort() {
      
      
      this.arr_sort = this.sort.split(",");
    },
    getorder(val) {
      
      
      return this.arr_sort.findIndex((m) => Number(m) === val + 1);
    },
  },
};
</script>
<style scoped lang="less">
.content {
      
      
  display: flex;
  flex-direction: column;
  margin-top: 10px;
  align-items: center;
  div {
      
      
    width: 100px;
    height: 100px;
    line-height: 100px;
    border-block: 1px solid #dedede;
  }
}
</style>

Realization effect:
Enter the string (4,5,6,1,2,3,7,8) and click the sort button to reorder the order of dom
insert image description here

Guess you like

Origin blog.csdn.net/qq_29184685/article/details/130281669
Recommended