programing

vue js에서 루프(복수의 루프)가 완료된 후 메서드를 호출하려면 어떻게 해야 합니까?

prostudy 2022. 8. 2. 22:12
반응형

vue js에서 루프(복수의 루프)가 완료된 후 메서드를 호출하려면 어떻게 해야 합니까?

내 vue 컴포넌트는 다음과 같습니다.

<template>
    <div class="row">
        <div class="col-md-3" v-for="item1 in items1">
            ...
        </div>
        <div class="col-md-3" v-for="item2 in items2">
            ...
        </div>
        <div class="col-md-3" v-for="item3 in items3">
            ...
        </div>
    </div>
</template>
<script>
    export default {
        ...
        computed: {
            items1() {
                const n = ... // this is object
                return n
            },
            items2() {
                const n = ... // this is object
                return n
            },
            items3() {
                const n = ... // this is object
                return n
            }
        },
        ...
    }
</script>

3개의 루프가 완료되면 메서드를 호출합니다.

따라서 이 메서드는 3개의 루프가 완료되면 실행됩니다.

어떻게 해야 하죠?

약속한 대로, 여기 예가 있습니다.

var counter = 0

const vm = new Vue({
  el: '#app',

  computed: {
    items1() {
      return {item1: 'value1', item2: 'value2'}
    },
    items2() {
      return {item1: 'value3', item2: 'value4'}
    },
    items3() {
      return {item1: 'value5', item2: 'value6'}
    }
  },

  methods: {
    callback() {
      counter++
      console.log('v-for loop finished')
      var numberOfLoops = 3
      if (counter >= numberOfLoops) {
        console.log('All loops have finished executing.')
        counter = 0
      }
    }
  },

  directives: {
    forCallback(el, binding, vnode) {
      let element = binding.value
      var key = element.key
      var len = 0

      if (Array.isArray(element.array)) {
        len = element.array.length
      }

      else if (typeof element.array === 'object') {
        var keys = Object.keys(element.array)
        key = keys.indexOf(key)
        len = keys.length
      }

      if (key == len - 1) {
        if (typeof element.callback === 'function') {
          (element.callback.bind(vnode.context))()
        }
      }
    }
  },

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id="app">
  <div class="row">
    <div class="col-md-3" v-for="(item, key) in items1" v-for-callback="{key: key, array: items1, callback: callback}">
      ...
    </div>

    <div class="col-md-3" v-for="(item, key) in items2" v-for-callback="{key: key, array: items2, callback: callback}">
      ...
    </div>

    <div class="col-md-3" v-for="(item, key) in items3" v-for-callback="{key: key, array: items3, callback: callback}">
      ...
    </div>
  </div>
</div>

언급URL : https://stackoverflow.com/questions/45213139/how-can-i-call-a-method-after-the-loopsmore-than-1-loop-complete-on-vue-js

반응형