在常见的博客中都会这样写到
created:在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图。
mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。
在实际的开发过程中我们会经常使用create方法,在页面还未渲染成html前,调用函数,从后端获取数据,在实现对页面的数据进行显示。比如说下面例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| created() {
if(this.$route.params.id) this.orderNo=this.$route.params.id this.getOrderInfo() }, methods:{ getOrderInfo(){ order.getOrderByNum(this.orderNo).then(resp=>{ this.order=resp.data.data.data console.log((this.order)) getDetailTeacher(this.order.teacherName).then( resp=>{ this.teacherName=resp.data.data.teacher.name console.log(this.teacherName) } )
}).catch(error=>{
}) },
|
哪我们在什么时候使用mounted方法?
mounted通常是在一些插件的使用或者组件的使用中进行操作 也就是页面渲染之后执行 通常情况下我们会在没有相应的点击事件,但需要在页面展示过程中去不断调用某一函数情况下使用。
比如说在常见的订单支付功能,我们点击立即付款后,跳转到付款页面。这是时候需要我们不断访问后端接口查看用户是否支付成功,支付成功后进行跳转。我们需要将查询函数的调用写在mounted函数中,并通过计时器不断调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| mounted() { this.timer1 = setInterval(() => { this.queryOrderStatus(this.payObj.out_trade_no) }, 3000); }, methods: { queryOrderStatus(orderNo) { orderApi.queryPayStatus(orderNo) .then(response => { if (response.data.success) { clearInterval(this.timer1) this.$message({ type: 'success', message: '支付成功! 💴' }) this.$router.push({ path: '/course/' + this.payObj.course_id }) } }) } }
|
定时器方法介绍
1 2 3
| this.time1=setInterval(()=>{ this.queryPayStatus(this.this.payObj.out_trade_no) },3000)
|
setInterval()有两个参数一个是要执行的函数,一个是要执行的时间间隔单位为毫秒,此处函数采用箭头函数
ES5 语法如下
setInterval(function(){ alert(“Hello”); }, 3000);
将定时器赋给time 对象
清除定时器 clearInterval(this.time1)