- 【MAC 上学习 Vue】Day 15. 项目中引入 props
- vue2.0项目中引入sass、less
- 【MAC 上学习 Vue】Day 10. 项目中引入 Vue R
- 【MAC 上学习 Vue】Day 11. 项目中引入 Mock
- 【MAC 上学习 Vue】Day 4. 项目中引入 iView
- 【MAC 上学习 Vue】Day 12. 项目中引入 Axios
- 【MAC 上学习 Vue】Day 13. 项目中引入 QRCod
- 【MAC 上学习 Vue】Day 14. 项目中引入 Map
- 【MAC 上学习 Vue】Day 9. 项目中引入 JS、CSS
- MAC上学习Vue---Day4. 项目中引入 iView 框架
组件通信
- 父组件通过 props 直接传递数据
- 子组件通过 $emit 触发传递数据
实现代码
1. 编写父组件
组件调用:
<child1 @change='getVal'></child1>
<child2 :count='msg'></child2>
组件引入:
import child1 from '@/components/child1'
import child2 from '@/components/child2'
组件注册:
components:{
child1,child2
},
完整代码:
<template>
<div class='page'>
<h1>父组件</h1>
<p>{{ msg }}</p>
<child1 @change='getVal'></child1>
<child2 :count='msg'></child2>
</div>
</template>
<script>
import child1 from '@/components/child1'
import child2 from '@/components/child2'
export default{
data(){
return {
msg:0
};
},
components:{
child1,child2
},
methods:{
getVal:function(val){
this.msg=val;
}
}
};
</script>
<style scoped>
</style>
2. 编写子组件 1
组件触发:
<button @click='fn'>单击子组件传值给父组件</button>
事件定义:
fn:function(){
this.$emit('change',this.smsg);
}
完整代码:
<template>
<div class='page'>
<h3>子组件</h3>
<button @click='fn'>单击子组件传值给父组件</button>
</div>
</template>
<script>
export default{
data(){
return {
smsg:'3'
};
},
methods:{
fn:function(){
this.$emit('change',this.smsg);
}
}
};
</script>
<style scoped>
.page{
border: 1px solid #000;
padding:10px;
}
</style>
3. 编写子组件 2
接收数据:
props:['count']
完整代码:
<template>
<div class='page'>
<h3>子组件2</h3>
<p>{{ count }}</p>
</div>
</template>
<script>
export default{
data(){
return {
};
},
props:['count']
};
</script>
<style scoped>
.page{
border: 1px solid #000;
padding:10px;
}
</style>
运行结果

网友评论