VueJS + Firebase与orderBy有关

时间:2016-09-26 19:21:37

标签: javascript firebase firebase-realtime-database vue.js

我是VueJS的新手,当我用VueJS方法调用OrderBy时,我遇到了问题。

我的基本应用程序正在检索显示在表格中的简单项目数组:

            <!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: function () {

                    return{
                        // Initialisation du tableau de users
                        users: []
                    };

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

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

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

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

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

            setTimeout(function () {
                ///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, function (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
            };

            // Fonction de récupération des users sur l'événement "child_added"
            usersRef.on('child_added', function (snapshot) {
                //console.log(snapshot.val());
                //On récupère la valeur ajoutée par Firebase
                var item = snapshot.val();
                item.id = snapshot.key();
                console.log('id ' + item.id);

                // On met à jour les users récupérés depuis firebase
                // dans les datas de vueJs
                vm.users.push(item);

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

            // Lecture de l'event suppression d'un node 
            usersRef.on('child_removed', function (snapshot) {

                //On récupère la valeur supprimée par Firebase
                var item = snapshot.val();
                // On récupère l'id de l'item supprimé
                item.id = snapshot.key();
                //console.log('id : ' + item.id);
                //console.log(item);

                // On modifie les datas de VueJs
                vm.users.removeValue('id', item.id);

                //Notification par Jquery
                $.notify(item.firstname + " " + item.name + " à été supprimé", "success", {position: "top right"});

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

                    </script>

                </body>
            </html>

你能帮助我理解为什么我的sortBy方法不起作用吗?感谢。

1 个答案:

答案 0 :(得分:0)

这可以解决这个问题。首先,您的sortBy数据需要位于数据对象中,而不是主要组件中:

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

你的代码中也有这个:

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

哪个不正确,应该是:

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

另外值得注意的是,您可能需要使用自定义过滤器,因为默认的orderBy过滤器似乎只对数值进行排序。

工作示例:http://www.webpackbin.com/Vk-AEaM6-