4-2 Vue 父子组件的数据传递

<!DOCTYPE html>
<html>
<head>
	<title>4-2 Vue 父子组件的数据传递</title>
	<script src="vue.js"></script>
</head>
<body>
	<!--
		1.通过属性转递数据
		2.单向数据流:父组件可以向子组件转递参数,但子组件不能修改父组件的内容
                  可以把父组件的值克隆到子组件里
        3.子组件向父组件传递值 emit:向外触发事件 然后需在template 监听该事件
	-->
	<div id="app">
		<!--count="0",转递的是字符串,:count="0",转递的是数字 因为加:就是js表达式-->
		<!--父组件通属性向子组件传递数据-->
		<counter :count="0" @change="handleIncreate"></counter>
        <counter :count="1" @change="handleIncreate"></counter>
        <div>{{total}}</div>
	</div>
	<script type="text/javascript">
		//定义一个局部组件
		var counter={
			//通过props接受你父组件传递的值 
			props:['count'],
			//将父组件的值克隆到子组件里this.count
			data:function(){
				return {
					number:this.count
				}
			},
			//局部组件自己的模板,并使用props变量
			template:'<div @click="handleClick">{{number}}</div>',
			methods:{
				handleClick:function(){
					//改变自己的值
					this.number+=2
                    this.$emit('change',2)
                    
				}
			}
		}
		var app = new Vue({
			el:'#app',
            data:{
                total:1
            },
			//注册局部组件,就可以使用了
			components:{
				counter:counter
			},
            methods:{
                handleIncreate:function(inc){
                    this.total+=inc
                }
            }
		})

		
	</script>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值