这篇文章主要介绍“vue子组件封装弹框只能执行一次的mounted如何解决”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“vue子组件封装弹框只能执行一次的mounted如何解决”文章能帮助大家解决问题。
vue子组件封装弹框只能执行一次的mounted
封装了一个子组件来处理弹框内容,发现只能执行一次,在父组件添加一个 v-if 即可,当每次弹框关闭的时候销毁掉该组件就没有问题了。
贴一下简易代码:
父组件:
<add-dialog v-if="addVisible" :dialogVisible="addVisible" @addClose="addClose"></add-dialog>
addClose () {
  this.addVisible = false
}子组件:
<template>
  <div class="box">
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      :before-close="handleClose">
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {
    dialogVisible: Boolean
  },
  watch: {
    dialogVisible: function () {
      this.$emit('addClose')
    }
  }
}
</script>vue mounted方法在什么情况下使用和js定时器使用
在常见的博客中都会这样写到
created:在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图。
mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。
在实际的开发过程中我们会经常使用create方法,在页面还未渲染成html前,调用函数,从后端获取数据,在实现对页面的数据进行显示。
比如说下面例子
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))
          //根据订单中的老师id,获取老师姓名
          getDetailTeacher(this.order.teacherName).then(
            resp=>{
              this.teacherName=resp.data.data.teacher.name
              console.log(this.teacherName)
            }
          )
        }).catch(error=>{
        })
      },我们在什么时候使用mounted方法?
mounted通常是在一些插件的使用或者组件的使用中进行操作 也就是页面渲染之后执行 通常情况下我们会在没有相应的点击事件,但需要在页面展示过程中去不断调用某一函数情况下使用。
比如说在常见的订单支付功能,我们点击立即付款后,跳转到付款页面。
这是时候需要我们不断访问后端接口查看用户是否支付成功,支付成功后进行跳转。
我们需要将查询函数的调用写在mounted函数中,并通过计时器不断调用。
   mounted() { //页面渲染之后执行,设置为3s一更新
      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
              })
            }
          })
      }
    }定时器方法介绍
this.time1=setInterval(()=>{
this.queryPayStatus(this.this.payObj.out_trade_no)
},3000)setInterval()有两个参数一个是要执行的函数,一个是要执行的时间间隔单位为毫秒,此处函数采用箭头函数
ES5 语法如下
setInterval(function(){ alert(“Hello”); }, 3000);将定时器赋给time 对象
清除定时器 clearInterval(this.time1)