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