Vue $emit与props的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue $emit与props的使用

闲适_   2022-05-28 我要评论

一、props 和 $emit

1、子组件向父组件传值,通过$emit 事件向父组件发送消息,将自己的数据传递给父组件。

2、props 可以在组件上注册一些自定义属性。父组件通过绑定该属性来向子组件传入数据,子组件通过 props 属性获取对应数据。

二、示例

1.父组件

// parent.vue
<template>
	<div>
      	<p>childMessage: {{childMessage}}</p>
      	<children :sendmessage='childMessage' @showMsg="updataMsg"></children>
	</div>
</template>

import children from '/*...*/'
export default{
	data () {
		return {
			childMessage: '父组件给子组件传值'
		}
	},
	methods: {
		updataMsg(message) {
			this.childMessage = message
			console.log(this.childMessage)
	components: {
		children
	}
}

2.子组件

// children.vue
<template>
	<div>
		// 通过按钮点击事件将子组件的值传给父组件
	    <button @click="sendtoParent">Click this Button</button>
	</div>
</template>
<script>
export default {
  props: ['sendmessage'],
  methods: {
  	sendtoParent() {
  		//$emit括号里的第一个参数为自定义事件
  		this.$emit('showMsg','子组件通过$emit给父组件传值')
  	}
  }
}
</script>

结果展示

父子组件通信之前

在这里插入图片描述

父子组件通信之后

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们