前端寫特效的時候必需要保證DOM是加載完畢的,以前我用組件生命週期的update寫,多有不便, 現發現自定義指令比較好,指令裏面也是有周期,能作到相對的分離,案例奉上javascript
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
*{padding: 0;margin:0;}
ul,li{list-style: none}
.sliderCon{
width: 800px;
height: 400px;
margin: 50px auto;
overflow: hidden;
font-family: "微軟雅黑";
position: relative;
}
.sliderCon ul{
position: absolute;
left: 0;
top: 0
}
.sliderCon ul li{
width: 800px;
height: 100%;
line-height: 400px;
text-align: center;
font-size: 50px;
color: #fff;
float: left;
/*font-weight: 700*/
}
.sliderCon ul li:nth-child(odd){
background: green
}
.sliderCon ul li:nth-child(even){
background: pink
}
</style>
</head>
<body>
<div id="app">
<div v-slider=lists class="sliderCon">
<ul>
<li v-for="(item,index) in lists">{{item.name}}</li>
</ul>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var vm=new Vue({
el:"#app",
data:{
lists:[
{name:"第一條"},
{name:"第二條"},
{name:"第三條"},
{name:"第四條"},
]
},
directives:{
slider:{
bind:function(el,obj){
},
update:function(el){
console.log("更新");
},
componentUpdate:function(){
console.log("組件更新");
},
inserted:function(el,obj){
// obj.value[0].name="4555656";
var ul=$(el).find("ul");
var li=ul.find("li");
ul.css("width",li.length*$(el).width());
var index=0;
setInterval(function(){
index>=li.length-1?index=0:index++;
ul.animate({"left":"-"+index*li.width()+"px"},300)
},1000)
}
}
}
})
</script>
複製代碼