1.父与子通信,通过属性传递值,代码如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<script src="js/vue.js"></script>
<title></title>
</head>
<body>
<div id="example">
<p>{{msg}}</p>
<parent></parent>
</div>
<script type="text/x-template" id="parentTpl">
<div>
<h1>这是父组件</h1>
<son name="zhangsan"></son>
</div>
</script>
<script type="text/x-template" id="sonTpl">
<div>
<h2>这是子组件</h2>
<p>{{"接收到的数据为"+name}}</p>
</div>
</script>
<script>
Vue.component('parent',{
template:'#parentTpl'
})
Vue.component('son',{
props:['name'],
template:'#sonTpl'
})
new Vue({
el: '#example',
data: {
msg: 'hello'
}
})
</script>
</body>
</html>
2.子与父通信,通过事件传递值,代码如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<script src="js/vue.js"></script>
<title></title>
</head>
<body>
<div id="example">
<parent></parent>
</div>
<script type="text/x-template" id="parentTpl">
<div>
<h1>父组件</h1>
<son @toParent="recMsg"></son>
</div>
</script>
<script type="text/x-template" id="sonTpl">
<div>
<h2>子组件</h2>
<input type="text" v-model="myMsg"/>
<button @click="sendToFather">发给父组件</button>
</div>
</script>
<script>
Vue.component('parent',{
template:'#parentTpl',
methods:{
recMsg:function(msg){
console.log('事件被触发msg is'+msg);
}
}
})
Vue.component('son',{
template:'#sonTpl',
data:function(){
return {
myMsg:''
}
},
methods:{
sendToFather:function(){
console.log("当前用户输入的内容为 "+this.myMsg);
this.$emit('toParent',this.myMsg)
}
}
})
new Vue({
el: '#example',
data: {
msg: 'hello'
}
})
</script>
</body>
</html>
3.利用
parent,
refs完成父子组件间通信
代码如下:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<script src="js/vue.js"></script>
<title></title>
</head>
<body>
<div id="example">
<parent></parent>
</div>
<script type="text/x-template" id="parentTpl">
<div>
<h1>这是父组件</h1>
<button @click="checkSonStatues">获取子组件的数据</button>
<hr/>
<son ref="mySon"></son>
</div>
</script>
<script type="text/x-template" id="sonTpl">
<div>
<h2>这是子组件</h2>
<button @click="checkParentStatues">获取父组件的数据</button>
</div>
</script>
<script>
Vue.component('parent',{
template:'#parentTpl',
data:function(){
return{
nowWork:'正在上班...'
}
},
methods:{
checkSonStatues:function(){
console.log(this.$refs.mySon.nowDong)
}
}
})
Vue.component('son',{
data:function(){
return{
nowDong:'正在学习...'
}
},
methods:{
checkParentStatues:function(){
console.log(this.$parent.nowWork)
}
},
template:'#sonTpl'
})
</script>
<script>
new Vue({
el: '#example',
data: {
msg: 'hello'
}
})
</script>
</body>
</html>