vue组件之间的通信示例

   


父组件传递数据给子组件=>

            通过在子组件中写入传递参数props:{    childMs:{  type:String  }  } 或者第二种写法props:[ 'childMs' ]

子组件传递数据给父组件=>

            子组件注册触发事件,父组件注册 触发子组件事件后的方法写在method里面 

源码贴上,有点小乱,不过可以很清楚看到组件之间是如何进行通信的

<!DOCTYPE html>
<html>
<head>
<title>组件之间的通信</title>
<meta charset="utf-8">
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript" src="./node_modules/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<account>
</account>
</div>
<template id="tel">
<div>
<h1>父组件</h1>
<login :child-ms="ms" ></login>
<login v-on:child-say="listenToMyBoy"></login>
<!--  -->
<p>页面中的两个button是由于渲染了两个login</p>
<p>do you like me ?{{childWords}}</p>
</div>
</template>


<template id="child-tel">
<div>
<!-- 父组件传过来的childMs数据 -->
<h2>{{childMs}}</h2>  
<button @click="onClickMe">传递数据给父组件</button>
</div>
</template>
<script type="text/javascript">
//定义一个账号组件
Vue.component('account' ,{
data(){
return {
ms:'我是源于父组件',  //传递给子组件数据
childWords:""
}
},
template:"#tel",//在这里使用登录组件
components:{
'login':{
template:"#child-tel",
props:{
childMs:{
type:String
}
},
data(){
return {
somedate:"我是子组件的数据传递给父组件",
}
},
methods:{
onClickMe:function(){
this.$emit('child-say',this.somedate);
}
}
}//组件的名字叫做login
},
methods:{
listenToMyBoy:function(somedate){
this.childWords = somedate;
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值