Vue组件封装以及父子组件的通信

应用场景:

这里举例一个简单的场景,在多个父组件中有个初始化密码的按钮,需要每次初始化之后弹出结果,成功时弹出初始化成功,并附有账号和密码,且可复制,初始化失败的是弹出错误提示“操作失败”,下面则封装这个初始化这个结果弹框提示:

 

 结果弹框子组件:

<style lang="scss" scoped>
.result-main{
  text-align: center;
  color: #666666;
  .result-tip{
    font-size: 24px;
    font-weight: 400;
  }
  p{
    margin: 10px 0;
  }
  .user-box{
    margin-top: 20px;
  }
}
.fail-main{
  text-align: center;
  margin-top: 30px;
}
</style>
<template>
  <Modal
    v-model="dialogVisible"
    class="page-modal"
    width="25%"
    :title="$t('auth.commonTip')"
    :scrollable="false"
    :footer-hide="true"
    class-name="vertical-center-modal"
    :styles="{ top: '-30px' }"
  >
    <!-- 新增成功的提示 -->
    <div class="result-main" v-if="type">
      <div>
        <!-- 新增成功 -->
        <!-- <p class="result-tip" v-if="add">{
   
   {$t("common.addSuccess")}}</p>
        <!-- 操作成功 -->
        <p class="result-tip">{
   
   {$t("common.success")}}</p>
      </div>
      <div class="user-box">
        <p>{
   
   {$t("common.accountName")}}:{
   
   {account}}</p>
        <p>{
   
   {$t("common.initPassword")}}:{
   
   {password}}</p>
      </div>
    </div>
    <!-- 新增失败的提示 -->
    <div class="fail-main" v-else>
      <p class="result-tip" v-if="add">{
   
   {$t("common.addFail")}}</p>
      <p class="result-tip">{
   
   {$t("common.addFail1")}}</p>
    </div>
    <div class="detailBackBtn">
      <Button type="primary" size="large" @click="copyPassword()" v-if="type">{
   
   {$t("common.copy")}}</Button>
      <Button type="primary" size="large" @click="close()" v-else class="copy-btn">{
   
   {$t("common.ensure")}}</Button>
    </div>
  </Modal>
</template>
<script>
export default {
  name: "randomCodeModal",
  components: {},
  props: {
    type: {
      type: Boolean,
      default: true,
    },
    add: {
       type: Boolean,
      default: false,
    },
     account: {
       type: String,
      default: '',
    },
     password: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      dialogVisible: false,
      newPassword: '',
      newAccount: ''
    };
  },
  computed: {
    companyId() {
      return localStorage.getItem("companyId");
    },
  },
  watch: {
    // 监听与计算
    password(newVal, oldVal) {
      this.newPassword = newVal
    },
    account(newVal, oldVal) {
      this.newAccount = newVal
    }
  },
  mounted() {},
  methods: {
    // 返回
    closeModal() {
      this.dialogVisible = false;
    },
    // 复制
    copyPassword() {
      // 模拟 输入框
      var cInput = document.createElement("input")
      var cInput = document.createElement("input");
      if (this.newAccount === '') {
        cInput.value = this.$t('common.password') + this.newPassword;
      } else {
         cInput.value = this.$t('common.accountName') + this.newAccount + this.$t('common.password');
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容
      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中(这里就是创建的input标签)
      // Input要在正常的编辑状态下原生复制方法才会生
      document.execCommand("copy");
      this.$message({
        type: "success",
        message: this.$t('common.copySuccess')
      });
    // 复制成功后再将构造的标签 移除
      document.body.removeChild(cInput);
      this.dialogVisible = false;
      this.$emit("afterComfirm");
      this.$emit("afterComfirm");
    },
    close() {
      this.dialogVisible = false;
      this.$emit("afterComfirm");
    }
  },
};
</script>

 父组件引入与使用

  • 引入
import randomCodeModal from './Modal/randomCodeModal.vue'
  • 使用
    <!-- 生成随机码---modal -->
    <randomCodeModal ref="randomCodeModal" :type="resultType" 
     @afterComfirm="closeModal" :add="false" :password="initPsw.password" 
    :account="initPsw.account"></randomCodeModal>
  • 给子组件传递props参数
  data() {
    return {
        resultType:false,
         initPsw: {},
    }
  }
  • 父组件调起子组件的逻辑

这里主要是用户点击确定要初始化密码的按钮之后,然后发送请求,根据请求后返回的结果去判断初始化成功与否,进而显示初始化的结果

    //点击确定初始话密码之后,请求数据最后显示初始化的结果modal
    confirmInit() {
      console.log('初始化确定')
      let params = {
        userId: this.addForm.userId
      }
      console.log('this.engineerId',this.engineerId)
      this.$store
        .dispatch("userPermit/initPassword", params)
        .then((response) => {
          const resultCode = response.statusCode;
          if (Number(resultCode) === 200) {
            this.initPsw = response.result
            this.$refs.randomCodeModal.dialogVisible = true
            this.resultType = true;
          } else {
            //初始化密码失败的请求
            this.$refs.randomCodeModal.dialogVisible =true
            this.resultType = false;
          }
        });
    }
  },

    
  • 参数说明 

 注意点:

  • 父组件向子组件传递数据时,如果传递的是字符串,需要定义在data中,不然子组件那边接收不到

猜你喜欢

转载自blog.csdn.net/weixin_46872121/article/details/125703916