javascript - In vue 2.0, if el does not exist, how to stop ajax from executing?
伊谢尔伦
伊谢尔伦 2017-06-26 10:55:39
0
2
724

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

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all (2)
学习ing

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 +")"); } }); } } });
    phpcn_u1582

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

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!