小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。
Vue2.x 组件 component 实练小栗子
上文我们学习了 Vue 组件的概念/组件传值/及小小例子, 本文我们上手演练几个小栗子, 实练一下
1. 进度条 progress
用到的知识点:
- 两个库 bootCDN https://www.bootcdn.cn/:
Vue.jsbootstrap.css - 父子组件传值: 父组件
v-on; 子组件:props$emit - 动画效果
requestAnimationFrame(callback)
这里有两个拓展, rAF 和 rIC
rAF:requestAnimationFrame笨栗子就用到了
MDN- window.requestAnimationFrame():
window.requestAnimationFrame()告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行
语法: window.requestAnimationFrame(callback); callback 即是要操作的函数方法
rIC:requestIdleCallback实验中的功能
MDN- window.requestIdleCallback():
window.requestIdleCallback()方法插入一个函数,这个函数将在浏览器空闲时期被调用。这使开发者能够在主事件循环上执行后台和低优先级工作,而不会影响延迟关键事件,如动画和输入响应。函数一般会按先进先调用的顺序执行,然而,如果回调函数指定了执行超时时间timeout,则有可能为了在超时前执行函数而打乱执行顺序。
语法: var handle = window.requestIdleCallback(callback[, options])
进度条实现 效果 :
进度条实现代码 及 每步注释
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.5.6/vue.js"></script>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet">
<style>
.progress {
margin: 21px;
width: 213px;
height: 21px;
}
</style>
</head>
<body>
<div id="box">
one: <my-progress :n="30" name="one" v-on:child="receive"></my-progress>
<!-- 2.监听 -->
two: <my-progress :n="50" name="two" v-on:child="receive"></my-progress>
{{ msg }}
</div>
<script>
var myProgress = {
props: ['n', 'name'], // 接收父组件传递过来的 n 值
data() {
return {
v: this.n, // 父组件传递过来的值不能更改, 所以用data中的 v 变量存储传过来的 n 值
}
},
created() {
// 在实例创建完成后, 被立即调用
// requestAnimationFrame(this.step)
this.timer = setInterval(() => {
// 进度条动画
this.v++
if (this.v === 100) {
clearInterval(this.timer)
this.$emit('child', this.name) // 1. 发送 给父组件调用 监听 v-on:child
}
}, 100)
},
template: `
<div class="progress">
<div class="progress-bar" v-bind:style="{width: v+'%'}">{{ v }}%</div>
</div>
`,
methods: {
step() {
this.v++
if (this.v <= 100) {
requestAnimationFrame(this.step)
}
},
},
}
new Vue({
el: '#box',
components: {
myProgress,
},
data: {
msg: '',
},
methods: {
receive(receiveName) { // 3. 接收
console.log(receiveName)
this.msg = '任务' + receiveName + '已完成.' // 4. 处理这个接收的值
},
},
})
</script>
</body>