Interactive table with Draggable feature supported by Bootstrap Vue

After tirelessly searching for a solution to drag and drop rows on a Bootstrap Vue table, I finally stumbled upon a functional version here: Codepen

I attempted to integrate this code into my own table:

Template:

<b-table  v-sortable="sortableOptions" @click="(row) => $toast.open(`Clicked ${row.item.name}`)"  :per-page="perPage" :current-page="currentPage"  striped hover :items="blis" :fields="fields" :filter="filter" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" :sort-direction="sortDirection" @filtered="onFiltered">
    <template slot="move" slot-scope="row">
        <i class="fa fa-arrows-alt"></i>
    </template>

    <template slot="actions" slot-scope="row">
        <b-btn :href="'/bli/'+row.item.id" variant="light" size="sm" @click.stop="details(cell.item,cell.index,$event.target)"><i class="fa fa-pencil"></i></b-btn>
        <b-btn variant="light" size="sm" @click.stop="details(cell.item,cell.index,$event.target)"><i class="fa fa-trash"></i></b-btn>
    </template>

    <template slot="priority" slot-scope="row">
        <input v-model="row.item.priority" @keyup.enter="row.item.focussed = false; updatePriority(row.item), $emit('update')" @blur="row.item.focussed = false" @focus="row.item.focussed = true" class="form-control" type="number" name="priority" >
    </template>
</b-table>

Script:

import Buefy from 'buefy';
Vue.use(Buefy);

const createSortable = (el, options, vnode) => {

    return Sortable.create(el, {
    ...options
    });
};

const sortable = {
    name: 'sortable',
    bind(el, binding, vnode) {
    const table = el.querySelector('table');
    table._sortable = createSortable(table.querySelector('tbody'), binding.value, vnode);
    }
};
export default {
    name: 'ExampleComponent',
    directives: { sortable },
    data() {
        let self = this;
        return {
            blis: [],
            currentPage: 1,
            perPage: 10,
            pageOptions: [ 5, 10, 15 ],
            totalRows: 0,
            sortBy: null,
            sortDesc: false,
            sortDirection: 'asc',
            sortableOptions: {
                chosenClass: 'is-selected'
            },
            filter: null,
            modalInfo: { title: 'Title', content: 'priority' },
            fields: [ 
                {
                    key: 'move',
                    sortable: true
                },
                ///...rest of the fields
            ]
    }
};

However, I keep encountering the following error message: Error in directive sortable bind hook: "TypeError: Cannot read property 'querySelector' of null"

What could be causing it to not locate the <tbody> element?

Edit: https://jsfiddle.net/d7jqtkon/

Answer №1

When you encounter the line of code

const table = el.querySelector('table');
, it is an attempt to retrieve the table element. The variable el actually represents the table element itself, which is why the method querySelector returns null.

By correctly assigning the table variable, the error will no longer occur:

  const table = el;    
  table._sortable = createSortable(table.querySelector("tbody"), binding.value, vnode);

Check out this working fiddle for reference.

Answer №2

const App = new Vue({
  el: "#app",
    directives: {
    sortable: {
      bind(el, binding, vnode) {
        let self =el
        Sortable.create(el.querySelector('tbody'),{
          ...binding.value,
          vnode:vnode,
          onEnd: (e) =>  {
            let ids = el.querySelectorAll("span[id^=paper_]")
            let order = []
            for (let i = 0; i < ids.length; i++) {
              let item = JSON.parse(ids[i].getAttribute('values'))
              //extract items checkbox onChange v-model
              let itemInThisData = vnode.context.items.filter(i => i.id==item.id)
              order.push({
                id:item.id,
                paper: item.paper,
                domain:item.domain,
                platform: item.platform,
                country:item.country,
                sort_priority: item.sort_priority,
                selectpaper:itemInThisData[0].selectpaper
              })
            }
            binding.value = []
            vnode.context.items = []
            binding.value = order
            vnode.context.items = order
            console.table(vnode.context.items)
          },
        });
      },    
    }
  },
  mounted() {
    this.totalRows = this.items?this.items.length: 0
  },
  methods:{
    updateFilteredItems(filteredItems) {
      // Trigger pagination to update the number of buttons/pages due to filtering
      this.totalRows = filteredItems.length
      this.currentPage = 1
    },
    log(){
      console.table(this.items)
      console.log(this)
    },
  },
  data(){
    return {
    rankOption:'default',
    totalRows: 1,
    currentPage: 1,
    filter: null,
    filterOn:[],
    sortBy:'paper',
    sortDesc: false,
    sortableOptions: {
      chosenClass: 'is-selected'
    },
    perPage: this.results_per_page==='Todo' ? this.items.length : this.results_per_page?this.results_per_page:50,
    pageOptions: [10, 50, 100, 500,'Todo'],
    sortDirection: 'asc',
    fields : [
      { key: 'paper', label: 'Support', sortable: true},
      { key: 'domain', label: 'Domain', sortable: true},
      { key: 'platform', label: 'Medium', sortable: true},
      { key: 'country', label: 'Country', sortable: true},
      { key: 'sort_priority', label: 'Rank', sortable: true},
      { key: 'selectpaper', label: 'Selection', sortable: true},
    ],
    items : [
      {
        id:12,
        paper: 'Expansion',
        domain:'expansion.com',
        platform: 'p',
        country:'Spain',
        sort_priority: '',
        selectpaper:false
      },
      {
        id:13,
        paper: 'The Economist',
        domain:'eleconomista.es',
        platform: 'p',
        country:'Spain',
        sort_priority: '',
        selectpaper:false
      },
      {
        id:14,
        paper: 'The Country',
        domain:'elpais.es',
        platform: 'p',
        country:'Spain',
        sort_priority: '',
        selectpaper:false
      }
    ]
  }
    }
})
<div id="app">
<template id="">
  <b-table
  :sort-by.sync="sortBy"
  :sort-desc.sync="sortDesc"
  v-sortable="items"
  show-empty
  small
  stacked="md"
  :items="items"
  :fields="fields"
  :current-page="currentPage"
  :per-page="perPage"
  :filter="filter"
  :filterIncludedFields="filterOn"
  :sort-direction="sortDirection"
  @filtered="updateFilteredItems"
  >
  <template v-slot:cell(selectpaper)="row">
    <span :id="'paper_'+row.item.id" :values="JSON.stringify(row.item)"></span>
    <b-form-group>
      <input  type="checkbox" @change="log" v-model="row.item.selectpaper" />
    </b-form-group>
  </template>
  <template v-slot:cell(sort_priority)="row" v-if="rankOption==='foreach-row'">
    <b-form-group>
      <b-form-input type="number"  @change="log"
      size="sm" placeholder="Rank" v-model="row.item.sort_priority">
    </b-form-input>
  </b-form-group>
  </template>
  </b-table>
</template>
</div>
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is preventing me from retrieving the parameter in the controller?

I could use some assistance with implementing pagination for displaying data. However, I am encountering issues in retrieving the parameter in the Controller Method. To provide more context, I have created a demo on CodePen which can be viewed at http://c ...

Passing state to getStaticProps in Next JSLearn how to effectively pass state

I am currently fetching games from IGDB database using getStaticProps and it's all working perfectly. However, I now have a new requirement to implement game searching functionality using a text input field and a button. The challenge I'm facing ...

Hide the div in PHP if the active variable is null

It looks like I'll need to implement Jquery for this task. I have a print button that should only appear if my array contains data. This is a simplified version of what I'm aiming to achieve: HTML <?include 'anotherpage.php'?> ...

Enhance the sequence of tweens by triggering them sequentially in response to rapid UI events

I am currently working on my three.js app setup and I am facing a challenge with creating a smooth transition between two models. The desired effect is to have the first model quickly scale down to zero, followed by the second model scaling up from zero t ...

Exploring the Differences: innerHTML versus appendChild for Loading Scripts

Struggling to dynamically load scripts onto the DOM? function addScript(fileName) { document.body.innerHTML += `<script src='components/${fileName}/${fileName}.js'></script>` } addScript('message-interface') I prefer th ...

The initialization of a static member in a JS class occurs prior to the loading of the cdn

After declaring this class member, I encountered the issue stating that MenuItem is not defined. It appears that the class initialization occurs before React or Material-UI finishes loading (I am currently loading them from their CDN using straight < ...

Delving Into the Mysteries of Bootstrap Modal Fading

After updating our Bootstrap plugins file to version 2.2.1, I encountered an issue with adding the 'fade' class to modals. Previously, we had been using data-* api references for modals but decided to switch over. However, when I tried to incorpo ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

How can I automate the process of clicking each button on a page one by one simultaneously?

I'm looking for a way to add a small delay of 1 second after each button is clicked in my code. I want the buttons to be clicked one after the other, not all at once. How can I achieve this until all buttons are clicked? Below is the current code: v ...

Can a specific section of an array be mapped using Array.map()?

Currently, I am working on a project utilizing React.js as the front-end framework. There is a page where I am showcasing a complete data set to the user. The data set is stored in an Array consisting of JSON objects. To present this data to the user, I am ...

How can I invoke a PHP script using AJAX?

I am currently working on implementing a feature that involves multiple tables where users can move table rows between the tables. I want to use ajax to call a php script that will update the database with the new values, specifically assigning a new paren ...

Firebase Admin refuses to initialize on a Next.js application that has been deployed on Firebase

Currently, I am facing an issue while attempting to deploy a Next JS app to Firebase hosting using the web framework option provided by firebase-tools. The problem arises when trying to initialize firebase-admin as it seems to never properly initialize whe ...

Trying to draw a comparison between a text box and an individual element within

I am having some difficulty comparing user-entered text in a textbox with an element in an array. function checkUserInput() { var str = imageArray[randomNumber]; var index = str.indexOf(document.getElementById('textBox').value); ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

Having trouble getting card animations to slide down using React Spring

I am currently learning React and attempting to create a slide-down animation for my div element using react-spring. However, I am facing an issue where the slide-down effect is not functioning as expected even though I followed a tutorial for implementati ...

Guide on invoking a JavaScript function within a jQuery upon a specific event, such as clicking a hyperlink

I have a website page where I display some important information. However, I want to make this text hidden initially and only visible when a user clicks on a specific link or button. I attempted to achieve this functionality using the following code snippe ...

Error encountered: The Bootstrap Carousel function is causing a TypeError as e[g] is not defined

I am attempting to build a dynamic bootstrap carousel using my json data, and I have implemented jQuery-Template for rendering. Essentially, I am generating the carousel slider on-the-fly from my json data with the help of jQuery-Template. Here is a snippe ...