search

Home  >  Q&A  >  body text

javascript - In vue 2.0, if el does not exist, how to stop ajax from executing?

Because a page has multiple ajax requests, or when you want to call a js on multiple pages, you don't need to use ajax, it will also request data, how to solve this problem. beforeCreate and mounted don't work. No matter whether <p id="el name"> exists or not, if you use the console to monitor it, the ajax request will still be issued. Please help me to clear up the confusion. Thank you very much.

        var rnotice =new Vue({
            el: '#right-notice',
            data: {sites:''},
            beforeCreate: function(){
                var _self = this;
                $.ajax({
                    type:'GET',
                    url:notice,
                    success:function(data){
                        _self.sites = eval("(" + data +")");
                    }
                })
            }
        });

Is it necessary to add a p judgment? for example:

if($('#right-notice').length>0){
   
  ajax....

}

Is there a better way

伊谢尔伦伊谢尔伦2712 days ago832

reply all(2)I'll reply

  • 学习ing

    学习ing2017-06-26 10:57:39

    First of all, you need to understand that html is html and js is js. Your code creates a new Vue object. This object does not depend on the right-notice element. It does not mean that if this element does not exist, the object cannot be instantiated. You need to Add your own logic to determine whether this element exists


     var rnotice =new Vue({
                el: '#right-notice',
                data: {sites:''},
                beforeCreate: function(){
                    if(document.getElementById("right-notice")) {
                        var _self = this;
                        $.ajax({
                            type:'GET',
                            url:notice,
                            success:function(data){
                                _self.sites = eval("(" + data +")");
                            }
                        });
                    }
                }
            });

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-06-26 10:57:39

    https://cn.vuejs.org/v2/guide... Life cycle diagram

    reply
    0
  • Cancelreply