Thursday, August 11, 2016

How to get VueJS, Rubaxa Sortable, and flask to work together

One of the problems I recently had integrating flask, sortable, and vuejs was that everytime I removed a object from the vuejs store, the sortable list would reset itself, sorting based on the data-id rather than the order of sortable. In the end, I added a function to Vue's watch and compiled events to sort sortable.
Vue.directive('sortable', {
    bind: function(){
        var vm = this.vm;
        var el = this.el;
        window.sortable = Sortable.create(el, {
            store: {
                get: function(sortable) {
                    const order = "{{ sort_order }}";
                    vm.sortOrder = order
                    return order ? order.split('|') : [];
                },

                set: function(sortable) {
                    const order = sortable.toArray();
                    vm.sortOrder = order.join('|')
                    $.ajax({
                        type: "POST",
                        url: '/sortorder',
                        data: {
                            'ordertype': 'todo_order',
                            'order': order.join('|')
                        }
                    })
                }
            },

            group: "todo_sort_order",
        });

    },
});

var vm =  new Vue({
    el:'#app',
    data:{
        todos: {{json_todo_list |safe}},
        sortOrder: [],
        orderedTodos:[]
    },
    methods: {

        deleteTodo: function(todo){
            _id = todo.id
            $("#" + _id)[0].reset();
            this.todos.$remove(todo);

            $.ajax({
                type: "POST",
                url: '/present/delete',
                data: {'id':_id},
                success: function(data) {
                }
            });
        },
    },
    watch: {
        'todos':function(val, oldVal){
            sortable.sort(this.sortOrder.split('|'));
        },
    },
    compiled: function(){
        sortable.sort(this.sortOrder.split('|'));
    }
})