Programing

Vue JS 구성 요소에 Div 추가 및 제거

c10106 2022. 5. 21. 08:24
반응형

Vue JS 구성 요소에 Div 추가 및 제거

나는 VueJS를 처음 접하는 사람인데, 지금 나는 도저히 이해할 수 없는 문제에 직면해 있다.버튼을 클릭하여 요소를 동적으로 추가 및 제거하고자 한다.어떻게 하면 이것을 작동시킬 수 있을까? 그래야 내가 마지막으로 추가한 div가 아니라 특정 div를 제거할 수 있다.나는 이것을 가지고 장난을 많이 쳤는데, 지금은 심지어 [Vue warn]:구성요소 렌더 함수에 무한 업데이트 루프가 있을 수 있다.나는 div=index를 설정하지 않고 대신 div.id등과 작업해야 할 것 같아.누가 이것 좀 도와줬으면 좋겠어.고마워요.

https://jsbin.com/zuquwej/edit?html,js,output

  <div id="app">

    <div
      v-for="(div, index) in divs"
      :key="div.id"
      :div="div=index"
    >
      <div class="row">
        <div class="col-12">Div {{div}}</div>
      </div>

      <button
        class="btn btn-danger"
        @click="deleteRow(index)"
      >Delete</button>

    </div>

    <button
      class="btn btn-success"
      @click="addRow"
    >Add row</button>

  </div>
const app = new Vue({

  el: '#app',

 data() {
    return {
      div: 0,
      divs: []
    };
  },

  methods: {
    addRow() {
      this.divs.push({
        div: this.div
      });
      console.log(this.divs);
    },
    deleteRow(index) {
      this.divs.splice(index, 1);
    }
  }

})

생성한 각 객체를 인덱스로 저장하고 구성 요소의divs재산그런데 배열 인덱스와는 달리 이 배열에서 요소를 곱해도 바뀌지 않는다.다음은 작업 예시:

<div
      v-for="div in divs"
      :key="div.id"
    >
      <div class="row">
        <div class="col-12">Div {{ div.name }}</div>
      </div>

      <button
        class="btn btn-danger"
        @click="deleteRow(div.id)"
      >Delete</button>

    </div>
const app = new Vue({ 
  el: '#app',

  data() {
    return {
      index: 0,
      divs: []
    };
  },

  methods: {
    addRow() {
      this.divs.push({
        id: this.index,
        name: 'div' + this.index,
      });
      this.index++;
    },
    deleteRow(index) {
      this.divs.splice(index, 1);
    }
  }

})

참조URL: https://stackoverflow.com/questions/61145426/adding-and-removing-divs-dynamically-in-vue-js-component

반응형