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

Ways to select a single checkbox when other checkboxes are selected in JavaScript

var select_all = document.getElementById("select_all"); //reference to select all checkbox var checkboxes = document.getElementsByName("testc"); //retrieving checkbox items //function to select all checkboxes select_all.addEventListener("change", function ...

struggling to access the value of a hidden field by using the parent class name

My coding experience so far looks like this- <tr class="chosen"> <td id="uniqueID">ABCDE5678</td> <input type="hidden" value="000005678" id="taxCode"> <td id="fullName">Z, Y</td> </tr> In this scenario, I need to ...

What are some potential causes of webpack-dev-server's hot reload feature not working properly?

Having an issue with my React project. When I try to use hot reload by running "npm start" or "yarn start" with webpack-dev-server configured (--hot flag), I'm getting the error message: [error message here]. Can anyone assist me in troubleshooting th ...

Looking for a way to trigger a function on JSTree's refresh event

I have searched through many posts here but cannot find what I am looking for. The version of JSTree that I am using is 3.3.3. My goal is to select a node after a create_node event triggers an AJAX request. Subsequently, JSTree fires the rename_node eve ...

How can I trigger a function after all nested subscriptions are completed in typescript/rxjs?

So I need to create a new user and then create two different entities upon success. The process looks like this. this.userRepository.saveAsNew(user).subscribe((user: User) => { user.addEntity1(Entity1).subscribe((entity1: EntityClass) => {}, ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

Detecting the failure of chrome.extension.sendRequest

Greetings Chrome Developers! I am wondering how one can determine when a chrome.extension.sendRequest call has not been successful. I attempted the following approach with no luck: chrome.extension.sendRequest({ /* message stuff here */ }, function(req){ ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Ways to Personalize Navbar in the Bulma Framework

How can I make the <router link> element in my navbar component full width? I'm also looking for keywords related to achieving this layout. Here is an image of the issue: I want a layout that spans the full width, regardless of the Chrome wind ...

Angular JS Introductory Module

Currently, I am encountering an issue in AngularJS 1.2.15 marked by $injector:modulerr. Interestingly, the application runs smoothly when hosted on a MAMP Apache server locally, but encounters errors when running on a node server, generating the error mess ...

Vue's getComponentName method now properly returns a function instead of returning 'undefined'

After tirelessly working on upgrading my project from Vue 2.6 to 2.7, I've managed to resolve most of the issues. However, there is a persistent problem with certain files that have cased props, triggering Vue to generate an error message known as a & ...

The Cross-Origin Request has been blocked due to the Same Origin Policy prohibiting access to the remote resource. The reason for this is that the CORS preflight response was unsuccessful

SERVERSIDE // Establishing Headers app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE"); res.header("Access-Control-Allow-Headers ...

What is the best way to pass compile-time only global variables to my code?

I am looking for a way to easily check if my code is running in development mode, and based on that information, do things like passing the Redux DevTools Enhancer to the Redux store. I know I can use process.env.NODE_ENV for this purpose, but I find it ...

What is the root of the data validation error occurring within this Laravel API?

I'm currently developing a registration form using Laravel 8 and Vue 3, with the back-end being an API. Within the users table migration file, I have the following structure: class CreateUsersTable extends Migration { public function up() { Sche ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

When the specified width is reached, jQuery will reveal hidden circular text upon page load instead of keeping it hidden

My current issue involves utilizing jQuery to hide circular text when the window width is below 760px. Although the functionality works as intended, there is a minor problem when the page loads under 760px width - the text briefly shows up before hiding ag ...

Experience the power of live, real-time data-binding for date-time input with AngularFire in 3 different

Here is a simplified version of my code snippet: tr(ng-repeat='entry in ds3.entries | orderBy:orderByField:reverseSort | filter:query as results') td input.screen(type='datetime-local', ng-model='entry.date_recei ...

Tips for adjusting the default selection in a second dropdown menu

I have a dilemma with my two dropdown lists, "optionone" and "optiontwo". I am trying to alter the default selected value from "option value=3>3" to option value=3 selected>3 when the user selects 2 from the first dropdown list ("optionone"). <script&g ...

How can you securely transfer the ARRAY OBJECT from JavaScript to PHP using Ajax?

I am attempting to send a Javascript Array Object via Ajax to PHP and then use that object as a true Array on the PHP side. My current approach has not been successful in terms of utilizing the incoming object as an Array within PHP; I can only parse it as ...

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...