Search code examples
javascriptjqueryvue.js

Functionality like $(document).ready( with Vue.js


I wrote a small code with Laravel, Vue and JQuery, which works fine. Now I want to remove JQuery and run all with Vue and Axios.

Here's my template:

 <ul id="product_list" class="vue-list-wrapper list-wrapper" data-rest="{{ route('rest_get_products', ["id"=>$product_type_id]) }}" data-pagination="0">
    <li v-for="item in items">
        <div class="item-name item-section">@{{ item.name }}</div>
        ...bla bla...
    </li>
</ul>

Following code actually works and I can render what I get from AJAX. I know how to apply Axios, no problem.

The point I'm confused about: How can I ensure $(document).ready( functionality with Vue?

(function(){
"use strict";

function init_vue_list(){

    var vue_list_handler = new Vue({
        el: '.vue-list-wrapper',
        data: {
            items: []
        },
        mounted: function (event) {
            var self = this;
            var ajax_url = this.$el.getAttribute('data-rest');

            $.ajax({ // No problem to convert this to Axios.
                url: ajax_url,
                method: 'GET',
                success: function (data) {
                    self.items = data;
                },
                error: function (error) {
                    console.log(error);
                }
            });
        },
        methods:{
            open_production:function(event){
                
            }
        }
    });

}

$(document).ready( // I'm confused how I can replace this with Vue.
    function(){
        if($('.vue-list-wrapper').length > 0) {
            init_vue_list();
        }
    }
);

})(document, $);

Solution

  • The recommended way by vue to do this is using mounted().

    mounted: function () {
      this.$nextTick(function () {
        // Code that will run only after the
        // entire view has been rendered
      })
    }
    

    Check: https://v2.vuejs.org/v2/api/#mounted