Vue.js父子组件通信-自定义事件

组件props用法:

props: {
	    // 基础类型检测 (`null` 意思是任何类型都可以)
	    propA: Number,
	    // 多种类型
	    propB: [String, Number],
	    // 必传且是字符串
	    propC: {
	      type: String,
	      required: true
	    },
	    // 数字,有默认值
	    propD: {
	      type: Number,
	      default: 100
	    },
	    // 数组/对象的默认值应当由一个工厂函数返回
	    propE: {
	      type: Object,
	      default: function () {
	        return { message: 'hello' }
	      }
	    },
	    // 自定义验证函数
	    propF: {
	      validator: function (value) {
	        return value > 10
	      }
	    }
	  }

自定义事件学习:

父组件通过属性将数据传递给子组件

子组件通过$on监听子组件事件,通过$emit来触发父组件的事件。

子组件代码:

<template>
	<div id="child">
		<p>子组件显示父组件输入:{{message}}</p>
		<button v-on:click="childMethod">子组件按钮 add</button>
	</div>
</template>

<script>
	export default {
		props:{
			message: {
				type: String,
				default: "hello child"
			}
		},
		data() {
			return {
				count:0
			}
		},
		methods:{
			childMethod:function() {
				this.count += 1
				// 当父组件事件触发之后,子组件通知父组件触发某一个事件。
				this.$emit("fatherEmit")
			}
		},
		components:{

		}
	}
</script>

<style>
</style>

父组件代码:

<template>
	<div id="father">
		<p>父组件的计数器{{fatherCount}}</p>
		父组件的输入:<input v-model="message">
		<!--父组件通过属性绑定给子组件传值-->
		<child v-bind:message = "message" v-on:fatherEmit = "fatherAdd"></child>
	</div>
</template>

<script>
	import Child from "../comment/Child"
	export default{
		data() {
			return {
				fatherCount:0,
				message:"hello"
			}
		},
		methods:{
			fatherAdd:function() {
				this.fatherCount += 1;
			}
		},
		components:{
			Child:Child
		}
	}
</script>

<style>
</style>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值