vue父子组件

vue父子组件

使用子组件类似于jsp动态引入页面,我们可以将一些可复用的功能或者页面封装成一个子组件,在需要用到时,在父组件中进行注册后,才能使用;
父子组件之间的通信是通过 e m i t 和 emit和 emiton以及props来进行数据的传递

<!DOCTYPE html>
<html>
<head>
	<title>父子组件数据传递</title>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	<style type="text/css">
		.parent{
			background:#0ff;
		}
	</style>
</head>
<body>
	<div id="app">
		<p>子组件随父组件改变</p>
		<input v-model="parentMsg" class="parent">
		<child :child_msg="parentMsg" ></child>
		<p>自定义事件</p>
		<p >{{total}}</p>
		<diy_child @parent="parentClick"></diy_child>
		<diy_child @parent="parentClick"></diy_child>
	</div>
	<script >
	//注册组件 子组件标签名不能出现大写字母 会出现无法识别标签问题
	Vue.component("child",{
		props:["child_msg"],
		template: "<p>子组件得到的数据---->{{child_msg}}</p>"
	})
	Vue.component("diy_child",{
		template:"<button @click='childClick'>{{count}}</button>",
		data:function(){
			return {count : 0}
		},
		methods:{
			childClick:function(){
				this.count++
				/*
				*$emit用来触发父组件的方法,也可以添加可选参数向父组件传递数据
				*父组件通过$on来监听$emit所传递的数据,二者的事件名必须保持一致
				*/
				this.$emit('parent') 

			}
		}
	})
	new Vue({
		el:"#app",
		data:{
			total:0,
			parentMsg : "这是父组件的数据"
		},
		methods:{
			parentClick:function(){
				this.total++
			}
		}
	})
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值