vue实现父子组件的互相传值及调用方法

本文介绍了在Vue中如何实现父组件调用子组件的方法并传递值,以及子组件如何返回值和调用父组件的方法。详细步骤包括组件命名、引用、值的传递以及使用$emit进行事件触发来实现通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.父级组件调用子组件及传值

(1)命名
组件命名使用驼峰命名法,如addStudent
引用时,用短横线连接,如:

<add-student></add-student>

2、引用
将组件页面import进入当前页面,并在componens里注册组件

import addStudent from "./components/addStudent";
export default {
	components: {
    	addStudent
  },
}

3、传值
父组件通过横线连接的方法,将当前页面的值传给子组件
子组件通过驼峰命名法,获取值

//父组件
<add-student
  :student-id="studentId"
></add-student>

data(){
	return{
		studentId:'001'
	}
}


子组件:

//子组件
export default {
  name: "addStudent",
  props: {
    studentId: {
      type: String,
      default: '',
    }
  },
}

//子组件输出为父组件传过来的值
console.log(this.studentId) //001

4、完整代码:

//父组件
<add-student
  ref="studentDialog"
  :is-show="showStudentDialog"
  :student-id="studentId"
></add-student>

//js
import addStudent from "./components/addStudent";
export default {
	components: {
    	addStudent
  },
}

//子组件
export default {
  name: "addStudent",
  props: {
    studentId: {
      type: String,
      default: '',
    }
  },
}

2、子组件返回值及调用父组件方法

1、返回值
子组件调用父组件的方法

this.$emit(父组件方法名,返回值)

<el-dialog
   title="选择学生"
   :visible.sync="isShow"
 >
 	 <el-table
        :data="studentData.content"
        @selection-change="handleSelectionChange"
        ref="dataTable"
        row-key="id"
      >
      ...
      </el-table>
</el-dialog>
export default {
	data(){
		stuSelection:[]
	},
	 props: {
	    isShow: {
	      type: Boolean,
	      default: false,
	    },
	 }
	methods: {
		cofirmStudent(){
			//stuSelection为选中的学生列表,返回选中的列表
			 this.$emit("selectStudent", this.stuSelection);
			 console.log(this.stuSelection) //[001,002]
		},
		closeDialog(){
			//调用关闭父组件关闭当前弹窗的方法
			this.$emit("closepop");
		}
	}
}

2、父组件命名方法
父组件用@xxx命名子组件可调用的方法

<add-student
  ref="studentDialog"
  :is-show="showStudentDialog"
  @closepop="closepop"
  @selectStudent="selectStudent"
></add-student>

//js
closepop() {
  this.showStudentDialog = false;
},
selectStudent(selectStudent) {
   console.log(selectStudent) //[001,002]
 },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值