1.父組件Appvue
1 <template> 2 <div id="app"> 3 <!-- 4 <ScrollBall @input="input" :value="posStart" color="green" :target="posTarget"></ScrollBall>--> 5 <!-- v-model 底層 實現@input="input" :value="posStart" 父組件中不須要寫 input函數 v-model底層會本身寫賦值--> 6 <ScrollBall v-model="posStart" color="yellow" :target="posTarget"></ScrollBall> 7 <ScrollBall ref="ball2" :value.sync="posStart" color="red" :target="posTarget"></ScrollBall> 8 <!-- 9 <ScrollBall @update:value1 ="input" :value1="posStart" color="red" :target="posTarget"></ScrollBall> 10 --> 11 <button @click="stopHandle"> stop </button> 12 </div> 13 </template> 14 15 <script> 16 import ScrollBall from "./components/ScrollBall.vue"; 17 export default { 18 name: "app", 19 beforeUpdate() { 20 // console.log(this.posStart); 21 }, 22 data() { 23 return { 24 posStart: 160, 25 posTarget: 400 26 }; 27 }, 28 components: { 29 ScrollBall 30 }, 31 methods: { 32 stopHandle(){ 33 this.$children.forEach(ele=>{ 34 ele.stop(); 35 }); 36 console.log(this.$children); 37 // this.$refs.ball2.stop(); 38 } 39 /* input(value) { 40 this.posStart = value; 41 }*/ 42 } 43 }; 44 </script> 45 46 <style lang="less"> 47 </style>
2.子組件node
1 <template> 2 <div class="ball" :style="style" :id="ballId"></div> 3 </template> 4 5 <script> 6 export default { 7 name: "ScrollBall", 8 mounted(){ 9 let ball = document.getElementById(this.ballId); 10 //頁面加載後讓小球運動 11 let fn = () => { 12 let left = this.value; 13 // console.log("left:",left); 14 if(left >= this.target){ 15 return cancelAnimationFrame(this.timer); 16 } 17 // left += 5; 18 this.$emit("input",left+1); //交給父親去改 19 this.$emit("update:value",left+1); 20 ball.style.transform = `translate(${left}px)`; 21 this.timer = requestAnimationFrame(fn); 22 } 23 this.timer = requestAnimationFrame(fn); //此函數只執行一次 24 }, 25 props: { 26 color: { 27 type: String, 28 default:"white" 29 }, 30 value:{ 31 type:Number, 32 default:0 33 }, 34 target:{ 35 type:Number, 36 default:0 37 } 38 }, 39 computed: { 40 style(){ 41 return {background:this.color} 42 }, 43 ballId(){ 44 return "ball"+this._uid; 45 } 46 }, 47 methods:{ 48 stop(){ 49 cancelAnimationFrame(this.timer); 50 } 51 } 52 }; 53 </script> 54 <style lang="less"> 55 .ball { 56 width: 100px; 57 height: 100px; 58 border: 1px solid #000; 59 border-radius: 50%; 60 box-sizing: border-box; 61 } 62 </style>
涉及的知識點:git