这篇文章主要介绍了vue中 $emit的用法,通过实例代码给大家介绍了子组件和父组件的相关知识,需要的朋友参考下吧

1、父组件可以使用 props 把数据传给子组件。

2、子组件可以使用 $emit 触发父组件的自定义事件。

vm.$emit( event, arg ) //触发当前实例上的事件
vm.$on( event, fn );//监听event事件后运行 fn;

例如子组件:

<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : isDetail ? '详情' : '编辑'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    class="YC-dialog YC-dialog_center"
    lock-scroll
    width="600px"

  >
    <el-row :gutter="15" class="">
      <el-form ref="elForm" :model="dataForm" size="medium" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
        <el-col :span="24">
          <el-form-item label="企业名称" prop="companyName">
            <el-input v-model="dataForm.companyName" placeholder="请输入" clearable :style="{ width: '100%' }" prefix-icon="" suffix-icon="">
              <template slot="prepend"></template>
              <template slot="append"></template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="租户姓名" prop="fullName">
            <el-input v-model="dataForm.fullName" placeholder="请输入" clearable :style="{ width: '100%' }" prefix-icon="" suffix-icon="">
              <template slot="prepend"></template>
              <template slot="append"></template>
            </el-input>
          </el-form-item>
        </el-col>
  <el-col :span="24">
          <el-form-item label="租户手机号" prop="mobile">
            <el-input v-model="dataForm.mobile" placeholder="请输入" clearable :style="{ width: '100%' }" prefix-icon="" suffix-icon="">
              <template slot="prepend"></template>
              <template slot="append"></template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="租户帐号" prop="enCode">
            <el-input v-model="dataForm.enCode" placeholder="请输入" clearable :style="{ width: '100%' }" prefix-icon="" suffix-icon="">
              <template slot="prepend"></template>
              <template slot="append"></template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="租户密码" prop="password">
            <el-input v-model="dataForm.password" placeholder="请输入" clearable :style="{ width: '100%' }" prefix-icon="" suffix-icon="">
              <template slot="prepend"></template>
              <template slot="append"></template>
            </el-input>
          </el-form-item>
        </el-col>


        <el-col :span="12">
          <el-form-item label="有效标识" prop="enabledMark">
            <el-switch v-model="dataForm.enabledMark" active-text="" inactive-text="" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="删除标志" prop="deleteMark">
            <el-switch v-model="dataForm.deleteMark" active-text="" inactive-text="" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24">

          <el-form-item label="过期时间" prop="expiresTime">
            <el-date-picker
              v-model="dataForm.expiresTime"
              placeholder="请选择"
              clearable
              :style="{ width: '100%' }"
              type="date"
              format="yyyy-MM-dd"
              value-format="timestamp"
            ></el-date-picker>
            <label style="color: #caa;">默认1年有效期</label>
          </el-form-item>
        </el-col>
       <!-- <el-col :span="24">
          <el-form-item label="数据库名字" prop="dbName">
            <el-input v-model="dataForm.dbName" placeholder="请输入" clearable :style="{ width: '100%' }" prefix-icon="" suffix-icon="">
              <template slot="prepend"></template>
              <template slot="append"></template>
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="dataForm.description"
              placeholder="请输入"
              show-word-limit
              :style="{ width: '100%' }"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 4 }"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import request from '@/utils/request';
import { getDictionaryDataSelector } from '@/api/systemData/dictionary';
import { previewDataInterface } from '@/api/systemData/dataInterface';
import ycu from '@/utils/yc.js'

export default {
  data() {
    return {
      visible: false,
      isDetail: false,
      dataForm: {
        companyName: undefined,
        enCode: undefined,
        fullName: undefined,
        ipAddress: undefined,
        ipAddressName: undefined,
        sourceWebsite: undefined,
        enabledMark: 1,
        deleteMark: 0,
        expiresTime:undefined ,
        dbName: undefined,
        description: undefined,
        password:undefined,
        mobile:undefined
      },
      rules: {}
    };
  },
  created() {


  },mounted() {

  }
  ,
  methods: {


    goBack() {
      this.$emit('refresh');
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.isDetail = isDetail || false;

      this.$nextTick(() => {
        this.$refs['elForm'].resetFields();
        if (this.dataForm.id) {
          request({
            url: '/api/System/baseUniTenant/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data;
          });
        }else{
          var ddc= new Date();

          ddc.setFullYear(ddc.getFullYear()+1)
         this.dataForm.expiresTime=ddc.getTime();
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (!this.dataForm.id) {
            request({
              url: '/api/System/baseUniTenant',
              loading:true,
              loadingText:"正在创建商户,请稍候……",
              method: 'post',
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refresh', true);
                }
              });
            });
          } else {
            request({
              url: '/api/System/baseUniTenant/' + this.dataForm.id,
              method: 'PUT',
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.$emit('refresh', true);
                }
              });
            });
          }
        }
      });
    }
  }
};
</script>

父组件:

<template>
  <div class="YC-common-layout">
    <div class="YC-common-layout-center">
      <el-row class="YC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="企业名称"><el-input v-model="query.companyName" placeholder="企业名称" clearable /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租户编码"><el-input v-model="query.enCode" placeholder="租户编码" clearable /></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租户姓名"><el-input v-model="query.fullName" placeholder="租户姓名" clearable /></el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="6">
              <el-form-item label="数据库名字"><el-input v-model="query.dbName" placeholder="数据库名字" clearable /></el-form-item>
            </el-col>
          </template>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else="">收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="YC-common-layout-main YC-flex-main">
        <div class="YC-common-head">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增租户</el-button>
            <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
          </div>
          <div class="YC-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top"><el-link icon="icon-ym icon-ym-Refresh YC-common-head-icon" :underline="false" @click="reset()" /></el-tooltip>
            <screenfull :isContainer="true" />
            <el-tooltip effect="dark" content="列设置" placement="top"><el-link icon="icon-ym icon-ym-options YC-common-head-icon" :underline="false" /></el-tooltip>
          </div>
        </div>
        <YC-table v-loading="listLoading" :data="list">
          <el-table-column prop="companyName" label="企业名称" align="left" />
          <el-table-column prop="fullName" label="租户姓名" align="left" /> 
          <el-table-column prop="enCode" label="租户手机号" align="left" />
          
          <el-table-column prop="expiresTime" label="过期时间" align="left" />
          <el-table-column prop="dbName" label="数据库名字" align="left" />
          <el-table-column prop="enabledMark" label="有效标识" align="center"  width="100px">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enabledMark" :active-value="1" :inactive-value="0" disabled class="table-switch" />
            </template>
          </el-table-column>
          <el-table-column prop="deleteMark" label="删除标志" align="center" width="100px">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.deleteMark" :active-value="1" :inactive-value="0" disabled class="table-switch" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="handleDel(scope.row.id)" class="YC-table-delBtn">删除</el-button>
            </template>
          </el-table-column>
        </YC-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <YC-Form v-if="formVisible" ref="YCForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
  </div>
</template>
<script>
import request from '@/utils/request';
import { getDictionaryDataSelector } from '@/api/systemData/dictionary';
import YCForm from './Form';
import ExportBox from './ExportBox';
import { previewDataInterface } from '@/api/systemData/dataInterface';

export default {
  components: { YCForm, ExportBox },
  data() {
    return {
      showAll: false,
      query: {
        companyName: undefined,
        enCode: undefined,
        fullName: undefined,
        dbName: undefined
      },
      defaultProps: {
        children: 'children',
        label: 'fullName'
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,

        sort: 'desc',
        sidx: ''
      },
      formVisible: false,
      exportBoxVisible: false,
      columnList: [
        { prop: 'companyName', label: '企业名称' },
        { prop: 'enCode', label: '租户编码' },
        { prop: 'fullName', label: '租户姓名' },
        { prop: 'ipAddress', label: 'IP地址' },
        { prop: 'ipAddressName', label: 'ip归属地' },
        { prop: 'sourceWebsite', label: '来源网站' },
        { prop: 'enabledMark', label: '有效标识' },
        { prop: 'deleteMark', label: '删除标志' },
        { prop: 'expiresTime', label: '过期时间' },
        { prop: 'dbName', label: '数据库名字' },
        { prop: 'description', label: '描述' }
      ]
    };
  },
  computed: {},
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.listLoading = true;
      let query = {
        ...this.listQuery,
        ...this.query
      };
      request({
        url: `/api/System/baseUniTenant`,
        method: 'get',
        data: query
      }).then(res => {
        this.list = res.data.list;
        this.total = res.data.pagination.total;
        this.listLoading = false;
        this.$nextTick(() => {
          this.tableHeight = '100%';
        });
      });
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/System/baseUniTenant/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData();
              }
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.YCForm.init(id, isDetail);
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query };
      request({
        url: `/api/System/baseUniTenant/Actions/Export`,
        method: 'POST',
        data: query
      }).then(res => {
        if (!res.data.url) return;
        window.location.href = this.define.comUrl + res.data.url;
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,

        sort: 'desc',
        sidx: ''
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,

        sort: 'desc',
        sidx: ''
      };
      this.initData();
    }
  }
};
</script>

子组件中:

this.$emit('refresh'); //调用父组件的 refresh 函数。

父组件:

 <YC-Form v-if="formVisible" ref="YCForm" @refresh="refresh" />
import YCForm from './Form'; //引入子组件

//父组件中定义的函数
 refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },

总结

以上所述是小编给大家介绍的关于vue中 $emit的用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我的支持!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐