programing

Vue.js, 어레이 항목 순서를 변경하고 DOM에서도 변경하십시오.

prostudy 2022. 4. 5. 22:31
반응형

Vue.js, 어레이 항목 순서를 변경하고 DOM에서도 변경하십시오.

Vue 인스턴스에는 4개의 값을 포함하는 "블록" 이름의 어레이가 있다.v-for를 사용하여 이 어레이를 DOM에 렌더링하는 경우:

<div class="block" @click="shuffleArray()">
    <div v-for="(number, index) in block">
        <span :class="[`index--${index}`]">{{ number }}</span>
    </div>
</div>

이렇게 하면 내부에 4개의 스팬이 있는 div가 생성되며, 각각 "index--0", "index-1" 등의 클래스가 있다.

이 옵션을 클릭하면 배열 변경 순서:

shuffleArray: function() {
    const shifted = this.block.shift();
    this.block.push( shifted );
}

값이 바뀌어도 실제 DOM에서는 움직이지 않는데, 클릭했을 때 어떻게 하면 DOM에서 스팬이 실제로 자리를 바꿀 수 있을까?각 스팬에는 스타일이 적용되므로 값들이 순서를 바꾼다는 것을 시각적으로 표현하고 싶다.

    span.index--0 {
        background-color: tomato;
    }

    span.index--1 {
        background-color: khaki;
    }

    span.index--2 {
        background-color:lavenderblush;
    }

    span.index--3 {
        background-color: lightcoral;
    }

아마도 DOM 조작이 필요하지 않은 CSS 전용 솔루션이 있을 것이다.

나는 다음과 같이 그 화려함을 만들기 위해 사용하는 것을 추천한다.

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#list-demo',
  data: {
    items: [1,2,3,4,5,6,7,8,9],
    nextNum: 10
  },
  methods: {
    randomIndex: function () {
      return Math.floor(Math.random() * this.items.length)
    },
    add: function () {
      this.items.splice(this.randomIndex(), 0, this.nextNum++)
    },
    remove: function () {
      this.items.splice(this.randomIndex(), 1)
    },
  }
})
.list-item {
  display: inline-block;
  margin-right: 10px;
}
.list-enter-active, .list-leave-active {
  transition: all 1s;
}
.list-enter, .list-leave-to /* .list-leave-active below version 2.1.8 */ {
  opacity: 0;
  transform: translateY(30px);
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="list-demo">
  <button v-on:click="add">Add</button>
  <button v-on:click="remove">Remove</button>
  <transition-group name="list" tag="p">
    <span v-for="item in items" v-bind:key="item" class="list-item">
      {{ item }}
    </span>
  </transition-group>
</div>

참조URL: https://stackoverflow.com/questions/57886649/vue-js-change-the-array-items-order-and-make-that-change-in-the-dom-as-well

반응형