三、组件间通信($parent $refs)

父组件要想获取子组件的数据:
①在调用子组件的时候,指定ref属性
<child-component ref="mySon"></child-component>

②根据指定的引用的名字 找到子组件的实例对象
this.$refs.mySon

子组件要想获取父组件的数据:
①直接读取
this.$parent

:::通过this.$refs拿到子组件的数据

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>组件间通信-01</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<dahua></dahua>
</div>
<script>
//vue提供的ref
Vue.component("dahua",{
data:function(){
return{
mySonName:""
}
},
methods:{
//通过$refs拿到指定的所引用的对应的组件的实例对象
getSonName:function(){
this.mySonName = this.$refs.mySon.name;
}
},
template:`
<div>
<h1>这是父组件</h1>
<button @click = "getSonName">获取子组件数据</button>
<span>{{mySonName}}</span>
<hr>
<xiaohua ref="mySon"></xiaohua>
</div>
`
})
// 创建子组件
Vue.component("xiaohua",{
data:function(){
return{
name:"小花"
}
},
template:`
<h1>这是子组件</h1>
`
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>

子组件通过$parent获取父组件的数据

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>组件间通信-02</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<dahua></dahua>
</div>
<script>
//创建子组件
Vue.component("dahua",{
data:function(){
return{
myName:"大花"
}
},
template:`
<div>
<h1>这是父组件</h1>
<hr>
<xiaohua></xiaohua>
</div>
`
})
//创建子组件
Vue.component("xiaohua",{
data:function(){
return{
msg:""
}
},
template:`
<div>
<h1>这是子组件</h1>
<p>{{msg}}</p>
</div>
`,
created:function(){
//在子组件创建完成时获取父组件的数据
//保存在msg中在p标签中显示
this.msg = this.$parent.myName;
}
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>

最新文章

  1. org.apache.log4j.Logger详解
  2. [转]HQL中的子查询
  3. oracle之报错:ORA-00054: 资源正忙,要求指定 NOWAIT
  4. POJ 2082 Terrible Sets
  5. spring对dao层的支持(datasource的作用)
  6. 【CC评网】2013.第41周 不求排版,简单就好
  7. 47. Permutations II
  8. JDBC学习总结(一)
  9. 时序列数据库武斗大会之 TSDB 名录 Part 1
  10. 不用标准库实现memmove,借助一个缓冲区temp,即使src和dest所指的内存有重叠也能正确拷贝
  11. Neuron:Neural activities in V1 create a bottom-up saliency map
  12. 实时同步rsync+inotify
  13. 转义字符\(在hive+shell以及java中注意事项):正则表达式的转义字符为双斜线,split函数解析也是正则
  14. 【机器学习基础】熵、KL散度、交叉熵
  15. Python 从入门到实践 试一试 参考代码
  16. C++标准库第二版笔记 3 和异常的理解 1
  17. JMeter高并发场景下存在请求无数据
  18. maxcompute笔记
  19. jQuery技巧笔记
  20. 解题:POI 2015 Pieczęć

热门文章

  1. empty()、isset()、is_null()的区别
  2. css渐变色兼容性写法
  3. Linux下安装chrome浏览器
  4. VMware Workstation key
  5. 特殊权限位:suid、sgid、sticky
  6. 1122. Hamiltonian Cycle (25)
  7. KeSetEvent
  8. Html5+ 开发APP 后台运行代码
  9. 运行biggan demo
  10. spring中试用junit4测试