首页 > 语言 > JavaScript > 正文

VUE DOM加载后执行自定义事件的方法

2024-05-06 15:30:29
字体:
来源:转载
供稿:网友

最近想用vue做一个小东西,谁知道一开始就遇到了一个棘手的问题:

首先我想在页面加载前通过ajax请求页面展示所需要的信息,于是我在created钩子函数里面请求了我想要的数据

created:function(){   var url="/indexitem";   var _self=this;   $.get(url,function(data){   _self.items=data;   });   $.get('/banner',function(data){   _self.banners=data;   });  }

这一步很顺利,接下来就是要将数据绑定到对应的元素中,我在这里需要将请求得到的图片地址绑定到轮播图对应的元素中,

我这里采用的是mui框架中提供的图片轮播(移动端,支持手势滑动),问题恰恰就这里:

<div id="slider" class="mui-slider" @click="greet()">  <div class="mui-slider-group mui-slider-loop">   <div class="mui-slider-item mui-slider-item-duplicate"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" :style="{backgroundImage: 'url(' + banners[banners.length-1].src+ ')',backgroundSize:'cover'}"></a></div>   <div class="mui-slider-item" v-for="cc in banners"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" :style="{backgroundImage: 'url(' + cc.src+ ')',backgroundSize:'cover'}"></a></div>   <div class="mui-slider-item mui-slider-item-duplicate"><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" :style="{backgroundImage:'url('+banners[0].src+')',backgroundSize:'cover'}"></a></div>  </div>  <div class="mui-slider-indicator">   <div class="mui-indicator mui-active"></div>   <div class="mui-indicator"></div>   <div class="mui-indicator"></div>   <div class="mui-indicator"></div>  </div>  </div>

我绑定完数据之后,发现轮播图失效了,因为我之前用原生js写的时候遇到过同样的问题,我当时的解决办法是等页面加载完成后重新进行滑动初始化,但是今天用vue我蒙了,试了很多生命周期函数也无法确保在页面加载完成后进行初始化。

vue.js更多的希望是通过数据绑定来代替直接通过dom操作,而vue并没有提供渲染完成的钩子。

所以我今天的解决办法是:setTimeout()

在实例化VUE对象后添加下面代码:

 setTimeout(function(){  console.log($('#slider').length);  var gallery = mui('.mui-slider');  gallery.slider({   interval: 3000//自动轮播周期,若为0则不自动播放,默认为0;  });  },1000);

以上这篇VUE DOM加载后执行自定义事件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持错新站长站。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选