フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

nuxtjsにvue-smooth-dndを適用する

はじめに

  • 下記のドラック&ドロップのライブラリをnuxtjsに適用してみる github.com

インストール

npm install vue-dnd-zone

コード

  • pages/test.vueファイルを作成する
<template>
  <div>
    <div class="simple-page">
      <Container @drop="onDrop">
        <Draggable v-for="item in items" :key="item.id">
          <div class="draggable-item">
            {{ item.data }}
          </div>
        </Draggable>
      </Container>
    </div>
  </div>
</template>

<script>
import { Container, Draggable } from 'vue-smooth-dnd'
import { applyDrag, generateItems } from '../utils/helpers'
export default {
  name: 'Simple',
  components: { Container, Draggable },
  data() {
    return {
      items: generateItems(50, (i) => ({ id: i, data: 'Draggable ' + i })),
    }
  },
  methods: {
    onDrop(dropResult) {
      this.items = applyDrag(this.items, dropResult)
    },
  },
}
</script>
  • utils/helpers.jsファイルを作成する
export const applyDrag = (arr, dragResult) => {
    const { removedIndex, addedIndex, payload } = dragResult
    if (removedIndex === null && addedIndex === null) return arr
  
    const result = [...arr]
    let itemToAdd = payload
  
    if (removedIndex !== null) {
      itemToAdd = result.splice(removedIndex, 1)[0]
    }
  
    if (addedIndex !== null) {
      result.splice(addedIndex, 0, itemToAdd)
    }
  
    return result
  }
  
  export const generateItems = (count, creator) => {
    const result = []
    for (let i = 0; i < count; i++) {
      result.push(creator(i))
    }
    return result
  }

実行結果

f:id:PX-WING:20210325232401p:plain