Having difficulty sorting data with Firebase in a VueJS project

I'm a newcomer to VueJS and I've encountered an issue when attempting to call the OrderBy method using VueJS.

My basic application is fetching a simple array of items that are being displayed in a table:

            <!DOCTYPE html>
            <!--
            To change this license header, choose License Headers in Project Properties.
            To change this template file, choose Tools | Templates
            and open the template in the editor.
            -->
            <html>
                <head>
                    <title>Test Vue.js</title>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
                    <link rel="icon" type="image/ico" href="img/favicon.ico" />

                </head>
                <body>
                    <div class="container">
                        <div class="row">
                            <div class="col-sm-12">
                                <h1>Test vueJs + Google Firebase</h1>
                                <hr class="" />
                            </div>
                        </div>
                        <div class="row">

                            <div class="col-sm-6">
                                <div class="panel panel-primary">
                                    <div class="panel-heading">Ajouter</div>
                                    <div class="panel-body">
                                        <form action="" id="formTest">
                                            <div class="input-group input-group-lg">
                                                <input name="name" id="name" type="text" class="form-control" placeholder="Nom">
                                            </div>

                                            <div class="input-group">
                                                <input name="firstname" id="firstname" type="text" class="form-control" placeholder="Prénom">
                                            </div>
                                            <div class="input-group">
                                                <input name="age" id="age" type="text" class="form-control" placeholder="Prénom">
                                            </div>

                                            <button type="submit" class="btn btn-success">Submit</button>

                                        </form>
                                    </div>
                                </div>
                            </div>

                            <div class="col-sm-6">
                                <div class="panel panel-primary">
                                    <!-- Default panel contents -->
                                    <div class="panel-heading">Liste</div>

                                    <!-- Table -->
                                    <table id="list1" class="table">
                                        <thead>
                                        <th>
                                            <a href="#" class="" @click="sortBy('id')">Id</a>
                                        </th>
                                        <th>
                                            <a href="#" @click="sortBy('name')">Nom</a>
                                        </th>
                                        <th v-on="click: sortKey = 'age'">Age</th>
                                        <th>Action</th>
                                        </thead>
                                        <tr v-for="user in users | orderBy sortKey">
                                            <td>{{user.id}}</td>
                                            <td>{{user.firstname}} {{user.name}}</td>
                                            <td>{{user.age}}</td>
                                            <td><button class="btn btn-primary" v-on:click="removeUser(user)">Supprimer</button></td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
                    <script src="js/bootstrap.min.js" type="text/javascript"></script>
                    <script src="js/vue.min.js" type="text/javascript"></script>
                    <script src="js/notify.min.js" type="text/javascript"></script>

                    <!------>
                    <script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-app.js"></script>
                    <script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-auth.js"></script>
                    <script src="https://www.gstatic.com/firebasejs/3.4.0/firebase-database.js"></script>

                    <!--<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>-->
                    <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
                    <script>

            // Initialize Firebase
            var config = {
                apiKey: "xxxxxxxxxxxxx",
                authDomain: "xxxxxxxxxxxxx.firebaseapp.com",
                databaseURL: "https://xxxxxxxxxxxx.firebaseio.com",
                storageBucket: "xxxxxxxxxxxxx.appspot.com",
                messagingSenderId: "xxxxxxxxxxxxxx"
            };
            firebase.initializeApp(config);

            var usersRef = new Firebase('https://testfirebase-b6e80.firebaseio.com/users/');

            var vm = new Vue({
                el: '#list1',
                data() {

                    return{
                        // Initializing users array
                        users: []
                    };

                },
                sortKey: '',
                ready() {
                    // this works
                    this.sortKey = 'name';
                },
                methods: {
                    updateUsers() {

                    },
                    removeUser(item) {
                        // Removing from Firebase
                        //console.log('item : ');
                        //console.log(item);
                        //console.log('---------------');
                        usersRef.child(item.id).remove();

                        // this works
                        this.sortKey = 'age';

                        //this.users.$remove(item);
                    },
                    sortBy(_sortKey) {

                        // but this doesn't
                        this.sortKey = _sortKey;
                        console.log("SortKey " + this.sortKey);
                    }
                }
            });

            setTimeout(() => {
                ///this doesn't work too
                vm.sortKey = 'age';
                console.log('timeout sortKey :'+vm.sortKey);
            }, 3000);

            Array.prototype.removeValue = function (name, value) {
                var array = $.map(this, (v, i) => {
                    return v[name] === value ? null : v;
                });
                this.length = 0; //clear original array
                this.push.apply(this, array); //push all elements except the one we want to delete
            };

            // Retrieving users on "child_added" event
            usersRef.on('child_added', (snapshot) => {
                //console.log(snapshot.val());
                //Fetching the value added by Firebase
                var item = snapshot.val();
                item.id = snapshot.key();
                console.log('id ' + item.id);

                // Updating the users retrieved from firebase
                // in VueJs data
                vm.users.push(item);

            }, (errorObject) => {
                console.log("The read failed: " + errorObject.code);
            });

            // Reading the node deletion event 
            usersRef.on('child_removed', (snapshot) => {

                //Fetching the value removed by Firebase
                var item = snapshot.val();
                // Retrieving the id of the deleted item
                item.id = snapshot.key();
                //console.log('id : ' + item.id);
                //console.log(item);

                // Modifying VueJs datas
                vm.users.removeValue('id', item.id);

                //Jquery Notification
                $.notify(item.firstName + " " + item.name + " has been deleted", "success", {position: "top right"});

            }, (errorObject) => {
                console.log("The read failed: " + errorObject.code);
            });

                    </script>

                </body>
            </html>

I would appreciate any assistance in understanding why my sortBy method isn't functioning properly. Thank you.

Answer №1

To solve this issue, you need to make a small adjustment. Ensure that your sortBy data is contained within your data object rather than in the main component:

data: function() {
    return {
        items: [],
        sortBy: 'name'
    }
}

Additionally, there seems to be an error in your code:

<th v-on="click: sortKey = 'age'">Age</th>

The correct syntax should be:

<th v-on:click="sortKey = 'age'">Age</th>

It's important to note that a custom filter may be necessary since the default orderBy filter only sorts numeric values.

For a demonstration, refer to this working example:

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

Design a button for uploading to Onedrive

Looking to implement an "upload to OneDrive" button on my website that will prompt a user authentication window for uploading files directly to their own OneDrive cloud. I've successfully done this with Google Drive but struggling to find a solution f ...

"Deactivate the escaping feature in PHP when using heredoc syntax

My PHP code generates minified JS output using the heredoc. Take a look at this snippet: function prerefresh(){$("#len").empty();predata.forEach(item)} I've highlighted that the {$ is causing issues with variable escaping in my heredoc. Is there a ...

Insert HTML content into an iframe with a callback function

We are receiving information from the backend server and need to transfer it to an iframe. In order to accurately set the height of the iframe to match the content, we must wait for the content to be loaded into the iframe. However, this process may not ha ...

The value of the keycode is consistently 229 for all keys

While using the regular textbox on my android device, I encountered some problems which are listed below. 1. The keypress event is not triggered on the android device. 2. The keycode value always returns as 229. What are some possible solutions to resolv ...

"The variables in the .env file are not reflecting the latest updates. What is the best way

Currently, I am in the process of developing an application using Quasar (Vue) where I have stored my database keys in a .env file. Recently, I encountered an issue when attempting to switch to another instance and updating the keys in the env file. Despit ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

Begin the file transfer process with Sails JS Skipper v0.10.5

Currently, I am successfully uploading files using skipper. However, I have encountered an issue with the saveAs option. Despite attempting to assign its value through a function, it doesn't seem to work as expected. How can I set the value of req.par ...

Ways to resolve the Face4 to Face3 issue

After stumbling across some old code, I discovered that it was mostly functional. var geom = new THREE.Geometry(); geom.vertices = testRect.verts(); for ( var i = 0; i < verts.length; i+=4 ) { geom.faceVertexUvs[0].push([ new THREE.Vector2 ...

When JavaScript evaluates special characters in HTML, it interrupts the function call within an AJAX response

Recently, I have been developing a custom form completion feature for a website/tool that I am working on. After successfully implementing the search functionality, which displays results below the input field, I wanted to enable users to select a result ...

JavaScript is throwing an error stating that the requestData is undefined, even though the

Hello, I am attempting to retrieve weather information based on the country and city using the openweather api. JSON is a new concept for me in coding, so please bear with me through this learning process. Below is the code snippet that I have been workin ...

Issue with Laravel and VueJs not rendering properly on Internet Explorer browser

My project runs smoothly on all browsers with the combination of Laravel and Vuejs, except for one - Internet Explorer. ...

Problem encountered when trying to use the sharp package in NuxtJS

I attempted to implement this code in my Nuxt project, but it encountered an issue during compilation. Within my plugin/sharp.js file: import vue from "vue" import sharp from "sharp" vue.use(sharp) And in my nuxt.config.js file: plugi ...

How to Build Node 0.4.7 on Ubuntu 11.10?

Having trouble compiling 0.4.7 for Heroku support as I am unable to enable ssl support required by express. I've tried installing libssl-dev and even attempted manual installation of openssl, but no luck so far. Any suggestions on how to get node up a ...

Spin a Collada model on its y-axis

I am struggling with a three.js scene that features a 3D Homer Simpson standing on a plane. My goal is to rotate him around his y-axis using the mouse. The code I have put together is almost there, with pieces borrowed from various sources. However, I am ...

Google is currently unable to provide the accurate latitude and longitude of the current position

I'm looking to incorporate geolocation functionality into my Laravel project. I've implemented this code, but it seems to be giving me slightly different latitude and longitude values. function getLocation() { var x = document.getElementById( ...

Error in Typescript: Function declarations are not allowed in blocks while in strict mode

When attempting to run a script, I encountered the following error message: Function declarations are not permitted in blocks in strict mode during targeting of the 'ES3' or 'ES5' version. The modules are automatically in strict mode. ...

Configuring Node.js HTTPS to function alongside HAPROXY

My goal is to establish communication between my nodejs app and HAPROXY using HTTPS. The plan is for nodejs to send a message to haproxy via https, and haproxy will then route the message accordingly. Initially, I had success with the request.js library, ...

Building a personalized version with core-js

I am currently in the process of developing a custom build using core-js. Following the instructions provided, I initiated the following commands: npm i core-js && cd node_modules/core-js && npm i The process seemed to go smoothly. Then, ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

Testing Angular 2: Ensuring Component Properly Calls Router with Accurate Arguments

I'm facing an issue with a child component that includes a button element with 'routerlink' attribute for navigation upon clicking. The button does not have a '(click)' handler, only the routerlink. Currently, I am writing a unit ...