vue 父组件与子组件直接的相互传值

1.父组件传值给子组件

html:  子组件:addFinancialUser 

<template>
  <div class="main-content adminStyle">
    <div class="condition" v-if="status">
      <el-row class="row-bg">
        <div class="condition-box">
          <el-col :span="20">
            <div class="col-2 col">
              <el-button @click="addFinancialUserBtn" size="small" type="primary">新增</el-button>
            </div>
          </el-col>
          <el-col :span="4" class="query-operate">
            <el-row>
              <el-col :span="18">
                <div class="col-1 col">
                  <label>机构名称:</label>
                  <el-input v-model="searchData.name" placeholder="请输入机构名称" class="ipt-name"/>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="query-btn">
                  <el-button type="primary" class="inquiry-btn" @click="inquiryBtn">查询</el-button>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </div>
      </el-row>
      <div class="table-list">
        <el-table :data="infoList"  :header-cell-style="{background:'#EEF5FD'}" border style="width: 100%">
          <el-table-column prop="id" min-width="20" label="序号"></el-table-column>
          <el-table-column prop="userName" min-width="50" label="登录账号"></el-table-column>
          <el-table-column prop="finName" label="机构名称"></el-table-column>
          <el-table-column prop="finType"  min-width="50" label="机构类型">
            
            <template slot-scope="scope">
              <span>{{ finTypeName[scope.row.finType - 1] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="finPhone" min-width="60" label="机构联系方式"></el-table-column>
          <el-table-column label="启用/冻结" min-width="50">
            <template slot-scope="scope">
              <el-switch 
                v-model="scope.row.status" 
                :width='52' 
                active-color="#FF8D31" 
                inactive-color="#E6E6E6"
                :active-value='1'
                :inactive-value='0'
                @change="switchChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="operate-btn">
                <el-button type="text" size="small" @click="resetPasswordBtn(scope.row.id)">重置</el-button>
                <el-button type="text" size="small" @click="editorBtn(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="delectBtn(scope.row.id)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
          <div class="pagination-per">
          <pagination :pagination="pagination" @changePage="handleChangePage"/>
        </div>
    </div>
    <addFinancialUser v-if="!status" :status="statustype" :oData="formData" @cancel="cancelFn" @confirm="confirmFn"></addFinancialUser>
  </div>
</template>

script:在父组件中,通过属性oData向子组件传递formData的参数

<script>
import { platform } from "@/api/platformApi.js";
import addFinancialUser from './addFinancialUser.vue'
export default {
  name: "paltformFinancial",
  components: {addFinancialUser},
  data() {
    return {
      status: true,
      statustype: 0,
      selectVal: [],
      name: "",
      selectList: [
        {
          value: "选项1",
          label: "启用"
        },
        {
          value: "选项2",
          label: "冻结"
        }
      ],
      searchData: {
        name: '',
        pageNum: 1,
        pageSize: 10
      },
      infoList: [],
      pagination: {},
      finTypeName: ['银行', '证券公司', '保险公司', '信托投资公司', '基金管理公司'],
      formData: {
        username: '',
        name: '',
        type: '',
        creditCode: '',
        address: '',
        phone: '',
        information: '',
      },
    };
  },
  created() {
    this.ajaxData();
      // this.pagination.total = this.infoList.length
  },
  methods: {
    // handleClick: function(obj) {
    //   this.$router.push({ path: "" });
    // },
    // btnFn() {
    //   this.ajaxData();
    // },
    cancelFn() {
      this.status = true;
    },
    confirmFn(data) {
    this.infoList = data;
this.status = true; this.ajaxData(); }, resetPasswordBtn(id) { platform.resetPassword(id).then(res => { if(res.data.code == '200') { this.$message({ type: "success", message: "密码重置成功!", duration: 3000, }); } }) }, delectBtn(id) { platform.userDel(id).then(res => { if(res.data.code == '200') { this.$message({ type: "success", message: "用户删除成功!", duration: 3000, }); } }) }, switchChange(value) { platform.liveOrDead(value.id).then(res => {}) }, inquiryBtn() { this.ajaxData(); }, handleChangePage: function(data) { this.infoList = data.tableData; this.pagination = data.pagination; }, // 请求 ajaxData() { this.infoList = []; platform.findFinancialQuery(this.searchData).then(res => { if (res.data.data.listData.length > 0) { this.infoList = res.data.data.listData; this.pagination = { pageNum: 1, pageSize: 10, total: res.data.data.total || 0, url: "/financial/sysUserManager/findFinancialQuery", params: this.searchData, method: "post" }; } else { } }) .catch(err => { console.log("error:", err); }); }, // handleRemove(file, fileList) { // console.log(file, fileList); // }, // handlePreview(file) { // console.log(file); // }, // handleExceed(files, fileList) { // this.$message.warning( // `当前限制选择 3 个文件,本次选择了 ${ // files.length // } 个文件,共选择了 ${files.length + fileList.length} 个文件` // ); // }, // beforeRemove(file, fileList) { // return this.$confirm(`确定移除 ${file.name}?`); // }, addFinancialUserBtn() { this.status = false; this.statustype = 0; this.formData = { username: '', name: '', type: '', creditCode: '', address: '', phone: '', information: '', } }, editorBtn(data) { this.status = false; this.statustype = 1; this.formData = { username: data.username, name: data.name, type: data.type, creditCode: data.creditCode, address: data.address, phone: data.phone, information: data.information, } } } }; </script>

子组件中:html

<template>
  <div>
    <el-header class="header">
      <span>金融机构用户管理</span>
      <i>|</i>
      <span>{{ status == 0 ? '新增用户' : '编辑用户'}}</span>
    </el-header>
    <el-main class="main">
      <el-form :model="formData" :rules="rules" ref="formItem" label-width="120px">
        <el-form-item label="登陆账号:" prop="username">
          <el-input v-model="formData.username" placeholder="请填写登陆账号" class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="机构名称:" prop="name">
          <el-input v-model="formData.name" placeholder="请填写机构名称" class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="机构类型:" prop="type">
          <!-- <el-input v-model="formData.type" placeholder="请填写机构类型" class="formInput"></el-input> -->
          <el-select v-model="formData.type" :popper-append-to-body="false">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="统一社会信用代码:" prop="creditCode">
          <el-input v-model="formData.creditCode" placeholder="请填写统一社会信用代码" class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="联系地址:" prop="address">
          <el-input v-model="formData.address" type="textarea" placeholder="联系地址" class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="机构联系电话:" prop="phone">
          <el-input v-model="formData.phone" placeholder="请填写机构联系电话:" class="formInput"></el-input>
        </el-form-item>
        <el-form-item label="机构简介:" prop="information">
          <el-input v-model="formData.information" type="textarea" placeholder="请填写机构简介" class="formInput"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <!-- <el-button @click="">取 消</el-button> -->
        <div class="primary-btn primary-btn1" @click="canceBtn">取消</div>
        <div class="primary-btn primary-btn2" v-if="status == 0" @click="submitAddForm">新增</div>
        <div class="primary-btn primary-btn2" v-if="status == 1" @click="submitEditorForm">编辑</div>
      </div>
    </el-main>
  </div>
</template>

 

script:通过props里定义属性,然后再data中接收来自父组件的属性值formData:this.oData

<script>
import { platform } from "@/api/platformApi.js";
export default {
  name: "addInfo",
  props: {
    status:{
      type: Number,
      default: 0
    },
    oData: {
      type: Object,
      default: {
        username: '',
        name: '',
        type: '',
        creditCode: '',
        address: '',
        phone: '',
        information: '',
      }
    }
  },
  data() {

    let regCode = /^[A-Z0-9]{18}$/;
    let regPhone = /^([0-9]{11})?$/;

    // 手机号码验证
    let validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else if (!regPhone.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    // 社会信用代码验证
    let validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入社会信用代码'));
      } else if (!regCode.test(value)) {
        callback(new Error('请输入正确的社会信用代码'));
      } else {
        callback();
      }
    };

    return {
      dialogFormVisible: false,
      formData: this.oData,
      rules: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请填写机构名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择机构类型', trigger: 'blur' }
        ],
        creditCode: [
          { validator: validateCode, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        information: [
          { required: true, message: '请填写机构简介', trigger: 'blur' }
        ]
      },
      typeList: [
        {
          value: '',
          label: "请选择类型"
        },
        {
          value: 1,
          label: "银行"
        },
        {
          value: 2,
          label: "证券公司"
        },
        {
          value: 3,
          label: "保险公司"
        },
        {
          value: 4,
          label: "信托投资公司"
        },
        {
          value: 5,
          label: "基金管理公司"
        }
      ],
      type: ''
    }
  },
  watch: {
    oData: {
      handler(newName) {
        this.formData = newName;
      },
      deep: true
    }
  },
  created() {
    // this.type = this.route.query.type;
    // this.formData = this,.
  },
  methods: {
   submitAddForm() {
      this.$refs['formItem'].validate(valid => {
        if (valid) {
          platform.addFinancial(this.formData).then(res => {
              if (res.data.code == '200') {
                this.dialogFormVisible = false;
                this.$message({
                  type: 'success',
                  message: '添加成功!',
                  duration: 2000,
                  onClose: () => {
                    this.$emit('confirm',this.formData)
                  }
                })
              }
            })
            .catch(err => {})
        } else {
          return false
        }
      })
    },
    submitEditorForm() {
      this.$refs['formItem1'].validate(valid => {
        if (valid) {
          platform.modifyFinancial(this.formData1).then(res => {
              if (res.data.code == '200') {
                this.dialogFormVisible1 = false;
                this.$message({
                  type: 'success',
                  message: '编辑成功!',
                  duration: 2000,
                  onClose: () => {
                    this.$emit('confirm')
                  }
                })
              }
            })
            .catch(err => {})
        } else {
          return false
        }
      })
    },
    canceBtn() {
      this.$emit('cancel')
    }
  }
};
</script>

 

 

 

2.子组件向父组件传值:通过触发事件传值 子组件通过某个动作触发父组件的自定义事件this.$emit('comfirm',this.formData)   

 父组件通过@confirm事件来触发confirmFn来接收来自子组件的data。

 

 


 

posted @ 2019-03-12 16:59  吴所事事  阅读(1039)  评论(0编辑  收藏  举报