vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue子组件修改父组件的值

vue之子组件如何修改父组件的值

作者:Leon_94

这篇文章主要介绍了vue之子组件如何修改父组件的值问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

如何在子组件中修改父组件的值

第一步

首先得保证父组件中有值吧

这是userManage.vue

data(){
    return{
        dialogCreate:'false'
    }
}

第二步

在父组件中引用子组件

import Form from './userCreate'

第三步

父组件中注册子组件并引用

<template>
    <app-form></app-form>
</template>
<script>
    export default{
        name:'user',
        components:{
            "app-form":Form
        },
        data(){
            return{
                dialogCreate:'false'
            }
        }
    }
</script>

第四步

把父组件的值绑定给子组件上

<app-form v-bind:dialogCreate = "dialogCreate" ></app-form>

第五步

既然父组件把值给了子组件了,子组件得接受和用吧

子组件

1.先接受
export default{
    props:['dialogCreate']
}
2.就可以直接在自组建中用了
<p>{{dialogCreate}}</p>

第六步

向父组件发射一个方法

比如我们在后台数据接收成功时,告诉父组件已经成功

this.$emit('success',false);

第七步

父组件接收到这个方法并且执行改变父组件的值

<app-form v-bind:dialogCreate = "dialogCreate" v-on:success="success(res)"></app-form>
methods: {
     check(){
         alert(1);
     },
     success(res){
        this.dialogCreate = res;
     }
}

最后,贴上源码

父组件

<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-menu"></i> 表格</el-breadcrumb-item>
                <el-breadcrumb-item>基础表格</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-row :gutter="22">
                <el-col :span="6">
                    <label>登录名:</label>
                    <el-input v-model="userName" placeholder="登录名" class="handle-input mr10"></el-input>
                </el-col>
                <el-col :span="6">
                    <label>姓名:</label>
                    <el-input v-model="realName" placeholder="姓名" class="handle-input mr10"></el-input>
                </el-col>
                <el-col :span="10">
                    <label>操作时间:</label>
                    <!-- <div class="block"> -->
                        <el-date-picker
                            v-model="value1"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    <!-- </div> -->
                </el-col>
            </el-row>
           <el-row :gutter="20" style="margin-top:10px">
                <el-col :span="6">
                    <label>状态:</label>
                    <el-select v-model="isClose" placeholder="匹配状态" class="handle-select mr10">
                        <el-option key="" label="请选择" value=""></el-option>
                        <el-option key="1" label="有效" value="0"></el-option>
                        <el-option key="2" label="无效" value="1"></el-option>
                    </el-select>
                </el-col>
                <el-button type="primary" icon="search" @click="search">搜索</el-button>
                <el-button type="success" icon="plus" @click="handleCreate">创建</el-button>
           </el-row>
        </div>
        <el-table :data="data" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
            <!-- <el-table-column prop="date" label="序号" sortable>
            </el-table-column> -->
            <el-table-column label="序号"
              type="index"
              :index="indexMethod" width="60px">
            </el-table-column>
            <el-table-column prop="userName" label="登录名" >
            </el-table-column>
            <el-table-column prop="realName" label="姓名" >
            </el-table-column>
            <el-table-column prop="isClose" label="状态" :formatter="states">
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称" width="120px">
            </el-table-column>
            <el-table-column prop="sex" label="性别" :formatter="sex">
            </el-table-column>
            <el-table-column prop="mobile" label="移动电话" width="120px">
            </el-table-column>
            <el-table-column prop="email" label="电子邮箱" width="120px">
            </el-table-column>
            <el-table-column prop="ts" label="操作时间" width="120px">
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template scope="scope">
                   <!--  <el-button size="small"
                            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                    <el-dropdown trigger="click">
                      <span class="el-dropdown-link">
                        操作<i class="el-icon-caret-bottom el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-button type="text" class="dropbtn"  @click="handleEdit(scope.$index, scope.row)">
                          查看
                        </el-button>
                        <el-button type="text" class="dropbtn">
                          编辑
                        </el-button>
                        <el-button type="text" class="dropbtn">
                          删除
                        </el-button>
                        <el-button type="text" class="dropbtn">
                          无效
                        </el-button>
                        <el-button type="text" class="dropbtn">
                          重置密码
                        </el-button>
                        <el-button type="text" class="dropbtn">
                          分配角色
                        </el-button>
                      </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change ="handleCurrentChange"
                    :current-page="cur_page"
                    :page-size="pageSize"
                    :page-sizes="[5, 10, 15, 30]"
                    layout="total,sizes,prev, pager, next,jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!-- 查看弹出框 -->
        <el-dialog
            title="查看"
            :visible.sync="dialogVisible"
            width="10%"
            :before-close="handleClose">
            <div class="form-inline">
                <span>&ensp;&ensp;登录名:</span>
                <label id="userNameCheck">{{signName}}</label>
            </div>
            <div class="form-inline">
                <span>&ensp;&ensp;&ensp;&ensp;姓名:</span>
                <label id="realNameCheck">{{name}}</label>
            </div>
            <div class="form-inline">
                <span>&ensp;&ensp;&ensp;&ensp;性别:</span>
                <label id="sexCheck">{{sexUser}}</label>
            </div>
            <div class="form-inline">
                <span>移动电话:</span>
                <label id="mobileCheck">{{mobile}}</label>
            </div>
            <div class="form-inline">
                <span>电子邮箱:</span>
                <label id="emailCheck">{{email}}</label>
            </div>
            <div class="form-inline">
                <span>&ensp;&ensp;&ensp;&ensp;状态:</span>
                <label class="green" id="isCloseCheck">{{isClose}}</label>
            </div>
            <div class="form-inline">
                <span>&ensp;&ensp;终端号:</span>
                <label class="" id="terminalNo">{{remark}}</label>
            </div>
            <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>
        <!-- 创建弹出框 -->
        <el-dialog
            title="提示"
            :visible.sync="dialogCreate"
            width="30%"
            :before-close="handleClose">
                <app-form v-bind:dialogCreate = "dialogCreate" v-on:success="success(res)"></app-form>
        </el-dialog>
    </div>
</template>
<script>
import Form from './userCreate'
    export default {
        name:'user',
        components:{
            "app-form":Form
        },
        data() {
            return {
                url: './static/vuetable.json',
                userName:'',
                realName:'',
                reservation:'',
                isClose:'',
                tableData: [],
                dataObj:{},
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                value1: ['',''],
                total:100,
                pageSize:10,
                dialogVisible:false,
                dialogCreate:false,
                signName:'123',
                name:'123',
                sexUser:'',
                mobile:'',
                email:'',
                isClose:'',
                remark:''
            }
        },
        created(){
            this.getData();
        },
        computed: {
            data(){
                const self = this;
                return self.tableData.filter(function(d){
                    let is_del = false;
                    for (let i = 0; i < self.del_list.length; i++) {
                        if(d.name === self.del_list[i].name){
                            is_del = true;
                            break;
                        }
                    }
                    return d;
                })
            }
        },
        methods: {
            check(){
                alert(1);
            },
            success(res){
                this.dialogCreate = res;
            },
            handleCurrentChange(val){
                this.cur_page = val;
                this.getData(val,this.pageSize);
            },
            handleSizeChange(val){
                this.pageSize = val;
                this.getData(this.currentPage,val);
            },
            getData(num,pageSize){
                let self = this;
                const params = new URLSearchParams();
                var startTime = self.value1[0];
                var endTime = self.value1[1];
                if(startTime == ''){
                    startTime = '';
                }else{
                    startTime = self.getTime(startTime);
                }
                if(endTime == ''){
                    endTime = ''
                }else{
                    endTime = self.getTime(endTime);
                }
                self.dataObj = {
                    userName:self.userName,
                    realName:self.realName,
                    isClose:self.isClose,
                    beginDate:startTime,
                    endDate:endTime
                }
                if(!num){
                    num = 1
                }
                if(!pageSize){
                    pageSize = 10
                }
                let data = self.param(self.dataObj,num,pageSize);
                params.append('param',data);
                if(process.env.NODE_ENV === 'development'){
                    self.url = '/s1/copUser/getUserList';
                };
                self.$axios.post(self.url, params).then((res) => {
                    self.tableData = res.data.data.list;
                    self.total = res.data.total;
                })
            },
            indexMethod(index) {
                return index + 1;
            },
            states(row,column){
                if(row.isClose == '0'){
                    return '有效'
                }else{
                    return '无效'
                }
            },
            sex(row){
                if(row.sex == '0'){
                    return '男'
                }else{
                    return '女'
                }
            },
            search(){
                this.is_search = true;
                this.getData();
            },
            formatter(row, column) {
                return row.address;
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            handleEdit(index, row) {debugger
                this.dialogVisible = true;
                this.signName = row.userName;
                this.name = row.realName;
                if(row.sex == 0){
                    this.sexUser = '男';
                }else{
                    this.sexUser = '女';
                }
                if(row.isClose == 0){
                    this.isClose = '有效'
                }else{
                    this.isClose = '无效'
                }
                this.mobile = row.mobile;
                this.email = row.email;
                this.remark = row.remark;
                // this.$message('编辑第'+(index+1)+'行');
            },
            handleCreate(){
                this.dialogCreate = true;
                debugger
            },
            handleDelete(index, row) {
                this.$message.error('删除第'+(index+1)+'行');
            },
            delAll(){
                const self = this,
                    length = self.multipleSelection.length;
                let str = '';
                self.del_list = self.del_list.concat(self.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += self.multipleSelection[i].name + ' ';
                }
                self.$message.error('删除了'+str);
                self.multipleSelection = [];
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 关闭对话框
            handleClose(done) {
                this.$confirm('确认关闭?')
                  .then(_ => {
                    done();
                  })
                  .catch(_ => {});
              }
        }
    }
</script>
<style scoped>
.handle-box{
    margin-bottom: 20px;
}
.handle-select{
    width: 120px;
}
.handle-input{
    width: 150px;
    display: inline-block;
}
.el-dropdown-link{
    color: #22A4E5!important;
    cursor: pointer;
}
.dropbtn{
    width: 100px;
    display: block;
    margin-left: 0px!important;
}
.el-dialog--small{
    width: 20%!important;
}
</style>

子组件

<template>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="登录名" prop="userName">
    <p>{{dialogCreate}}</p>
    <el-input v-model="ruleForm.userName" v-on:change="vaildInput(this)"></el-input>
  </el-form-item>
  <el-form-item label="姓名" prop="realName">
    <el-input v-model="ruleForm.realName" v-on:change="vaildInput(this)"></el-input>
  </el-form-item>
  <el-form-item label="性别" prop="sex">
    <el-radio-group v-model="ruleForm.sex">
      <el-radio label="男" value="0"></el-radio>
      <el-radio label="女" value="1"></el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="移动电话" prop="mobile">
    <el-input v-model="ruleForm.mobile" v-on:change="vaildInput(this)"></el-input>
  </el-form-item>
  <el-form-item label="电子邮箱" prop="email">
    <el-input v-model="ruleForm.email" v-on:change="vaildInput(this)"></el-input>
  </el-form-item>
  <el-form-item label="状态" prop="valid">
    <el-radio-group v-model="ruleForm.valid">
      <el-radio label="有效"></el-radio>
      <el-radio label="无效"></el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item label="用户终端号" prop="remark">
    <el-input v-model="ruleForm.remark" v-on:change="vaildInput(this)"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
    <el-button @click="resetForm('ruleForm')">重置</el-button>
  </el-form-item>
</el-form>
</template>
<script>
// import Vue from 'vue';
// import Router from 'vue-router';
    let Base64 = require('js-base64').Base64;
  export default {
    props:['dialogCreate'],
    data() {
      return {
        ruleForm: {
          userName: '',
          realName:'',
          mobile:'',
          email:'',
          remark:'',
        },
        sex:'',
        valid:'',
        url:'/s1/copUser/addUser',
        dataObj:{},
        rules: {
          userName: [
            { required: true, message: '请输入登录名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          realName: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          mobile: [
            { required: true, message: '请输入移动电话', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入电子邮箱', trigger: 'blur' }
          ],
          valid: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
          remark: [
            { required: true, message: '请填写用户终端号', trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {debugger
        let self = this;
        console.dir(self);
        const params = new URLSearchParams();
        let sex1 = '',isClose1 = '';
        if(self.ruleForm.sex == '男'){
            sex1 = 0;
        }else{
            sex1 = 1;
        }
        if(self.valid = '有效'){
            isClose1 = '1';
        }else{
            isClose1 = '0';
        }
        let psw = Base64.encode('123456');
        self.dataObj = {
            "userName":self.ruleForm.userName,
            "realName":self.ruleForm.realName,
            "sex":sex1,
            "passWord":psw,
            "mobile":self.ruleForm.mobile,
            "email":self.ruleForm.email,
            "remark":self.ruleForm.remark,
            "isClose":self.ruleForm.isClose
        }
        let data = self.paramSingle(self.dataObj);
        console.log(data);
        params.append('param',data);
        if(process.env.NODE_ENV === 'development'){
                self.url = '/s1/copUser/addUser';
            };
        this.$refs[formName].validate((valid) => {
          if (valid) {
            self.$axios.post(self.url, params).then((res) => {
                if(res.code == '0000'){
                    this.$emit('success',false);
                    this.$message.success({
                          message: res.msg
                        });
                }else{
                    this.$message.error(res.msg);
                }
                });
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      vaildInput(elem){
        console.log(this.$refs.value);
      }
    }
  }
</script>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文