Показать сообщение отдельно
  #7 (permalink)  
Старый 10.11.2022, 11:58
Аватар для Aetae
Тлен
Отправить личное сообщение для Aetae Посмотреть профиль Найти все сообщения от Aetae
 
Регистрация: 02.01.2010
Сообщений: 6,491

С render функцией это можно сделать примерно так:
<div id="app">
<v-sort>
   <v-line uid="1">1 бла бла бла — много html идет в слот </v-line>
   <v-line uid="2">2 бла бла бла — много html идет в слот </v-line>   
   <v-line uid="3">3 бла бла бла — много html идет в слот </v-line>
</v-sort>
</div>

<script src="https://unpkg.com/vue@2"></script>
<script>
function addListener(options, type, listener) {
  if (!options || !type || !listener)
    return;
  
  if (!options.listeners) 
    options.listeners = {};
  
  if (!options.listeners[type]) 
    options.listeners[type] = listener;
  else if (Array.isArray(options.listeners[type])) 
    options.listeners[type].push(listener);
  else 
    options.listeners[type] = [options.listeners[type], listener];
  
  return options;
}

Vue.component('v-sort', {
  data() {
    return {
      keyCounter: 0,
      events: ['up', 'down'],
      children: []
    }
  },
  render(h) {
    return h('div', this.children.map(
      ({vNode, key}) => h('div', { key }, [vNode])
    ));
  },
  created() {
    this.children = this.getChildren();
  },
  methods: {
    getNewKey() {
      return this.keyCounter++;
    },
    getChildren() {
      const vNodes = this.$slots.default?.filter(vNode => vNode.componentOptions);
      
      if (!vNodes?.length) 
        return [];

      return vNodes.map(vNode => {
        const key = this.getNewKey();
        
        this.events.forEach(event => addListener(
          vNode.componentOptions, 
          event, 
          (...args) => this[event](key, ...args)
        ));
        
        return {
          key,
          vNode
        };
      });
    },
    findIndexByKey(key) {
      return this.children.findIndex(child => key === child.key);
    },
    up(key) {
      const index = this.findIndexByKey(key);
      if (index < 1) return;
      this.children.splice(index - 1, 2, this.children[index], this.children[index - 1]);
    },
    down(key) {
      const index = this.findIndexByKey(key);
      if (index === -1 || index > this.children.length - 2) return;
      this.children.splice(index, 2, this.children[index + 1], this.children[index]); 
    }
  }
})

Vue.component('v-line', {
  template: `<p>
    <button @click="$emit('up')">up</button>
    <slot/>
    <button @click="$emit('down')">down</button>
  </p>`
});

new Vue().$mount('#app')
</script>


Конечно гораздо лучше было бы если бы не нужно было слушать события из подкомпонентов, а просто рисовать кнопки прямо из компонента sort.)
__________________
29375, 35

Последний раз редактировалось Aetae, 10.11.2022 в 12:03.
Ответить с цитированием