系列文章目录
Vue基础篇一:编写第一个Vue程序 Vue基础篇二:Vue组件的核心概念 Vue基础篇三:Vue的计算属性与侦听器 Vue基础篇四:Vue的生命周期(秒杀案例实战)
文章目录
系列文章目录一、生命周期图示与说明二、生命周期的例子--秒杀组件2.1 设计思路2.2 组件代码2.3 实战效果
总结
一、生命周期图示与说明
生命周期钩子函数说明应用
beforeCreate创建前:组件刚被创建,但访问不到data当中的属性以及methods当中的属性和方法可以在当前生命周期创建一个loading,在页面加载完成之后将loading移除created创建后:会遍历data中所有的属性,给每一个属性都添加一个getter、setter方法,将data中的属性变成一个响应式属性可以进行前后端数据的交互(ajax请求)beforeMount挂载前:模板与数据进行结合,但是还没有挂载到页面上可以在当前生命周期中进行数据最后的修改mounted挂载后:数据和模板进行相结合,并且已经挂载到页面上可以在当前生命周期中获取到真实的DOM元素beforeUpdate更新前:会将更新的数据与模板进行相结合,但是并没有挂载到页面上可以在当前生命周期中做状态处理,但千万不可更改依赖数据updated更新后:数据与模板进行相结合,并且将更新后的数据挂载到了页面上可以在当前生命周期中获取到最新的DOM结构,但千万不可更改依赖数据beforeDestroy销毁前:组件实例将被销毁可以在当前生命周期中进行事件的解绑 监听的移除 定时器的清除等操作destroyed销毁后:组件实例已销毁执行了destroy操作,后续就不再受vue控制了
二、生命周期的例子–秒杀组件
2.1 设计思路
设定一个秒杀开始时间和秒杀按钮。获取当前时间,与秒杀开始时间进行比对,计算出时间差(秒)并显示。当前时间小于秒杀开始时间时,秒杀按钮不可使用。当前时间超过秒杀开始时间时,秒杀按钮变为可以点击。
2.2 组件代码
<template>
<div>
{{ log("render") }}
当前时间:{{ now }}
<button :disabled="!start">{{ start ? "秒杀" : "等待中" }}
</button>
<br />
秒杀时间:{{ startTime }}
<br />
离秒杀还剩:{{ second }}秒
</div>
</template>
<script>
import moment from "moment";
export default {
data: function () {
console.log("data");
this.moment = moment;
this.log = window.console.log;
return {
now: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
start: false,
startTime: moment(
new Date(new Date().setSeconds(new Date().getSeconds() + 30))
).format("YYYY-MM-DD HH:mm:ss"),
second: 0,
};
},
watch: {
now() {
this.second =
(new Date(this.startTime.replace(/\\-/g, "\\/")) -
new Date(this.now.replace(/\\-/g, "\\/"))) /
1000;
if (this.second <= 0) {
this.second = 0;
this.start = true;
}
},
},
beforeCreate() {
console.log("beforeCreate");
},
created() {
console.log("created");
},
beforeMount() {
console.log("beforeMount");
},
mounted() {
console.log("mounted");
this.startClock();
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log("updated");
},
beforeDestroy() {
console.log("beforeDestroy");
clearInterval(this.clockInterval);
},
destroyed() {
console.log("destroyed");
},
methods: {
startClock() {
this.clockInterval = setInterval(() => {
this.now = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
}, 1000);
},
},
};
</script>
2.3 实战效果
总结