vue子组件封装弹框只能执行一次的mounted问题及解决

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue子组件封装弹框只能执行一次的mounted问题及解决

给你六圆钱   2023-03-23 我要评论

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: '支付成功! 
      

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们