Vue组件父子间通信01
2024-10-07 09:51:00
子组件传递数据 用户已经登录
父组件接收数据 并显示列表,未登录不显示列表
/*
有两个组件,分别是main-component,header-component.
main-component是由header-component和一个列表(有5条数据 [100,200,300,400,500]),
header-component是由一个h1的标签:'这是页头',有一个数据isUserLogin:true
在渲染main-component时候,读取header-component在挂载完毕之后通过事件传递来的数据(isUserLogin),根据该数据的真假来决定列表是否显示.
<child-component @myEvent="recvMsg">
</child-component>
this.$emit('myEvent',myPhone)
*/
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>子与父通信</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<main-component></main-component>
</div>
<script> //创建父组件
Vue.component("main-component",{
data:function(){
return{
myList:[1,2,3,4,5],
isUserLogin:true
}
},
methods:{
recvMsg:function(msg){
this.isUserLogin = msg;
}
},
template:`
<div>
<header-component @checkUserLogin="recvMsg"></header-component>
<ul v-if="isUserLogin">
<li v-for="tmp in myList">{{tmp}}</li>
</ul>
</div>`
})
//创建子组件
Vue.component("header-component",{
//data属性中保存用户已经登录
data:function(){
return{
isLogin:false
}
},
//通过$emit在挂载完成后把用户已经登录的值发传递给父组件
mounted:function(){
this.$emit("checkUserLogin",this.isLogin);
},
template:`
<div>
<h1>这是页头</h1>
</div>
`
})
// new一个vue实例
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>
最新文章
- UITextView 输入字数限制
- [kohana] kohana3.2,如何兼容PDO数据库连接方式
- git命令笔记2
- Javascript设置广告和时间表和数组的学习
- MySQL 命令杂记
- gitlab配置邮件通知
- ZOJ Problem Set - 3640 Help Me Escape
- oracle 常用SQL语法手册
- iOS8新特性之基于地理位置的消息通知UILocalNotification
- QEMU-KVM自己主动创建虚拟机,以指定IP构造
- Session中StateServer的使用方法
- oracle pl/sql 变量
- webstorm2017破解
- C# 微信开发-----微信会员卡(一)
- Java通过NIO实现快速文件拷贝的代码
- python--sort()和sorted()高级排序
- 在.NET程序中实现HttpServer功能
- Visual Studio 工具选项设置
- 类变量的初始化时机(摘录自java突破程序员基本功德16课)
- 洛咕 P3338 [ZJOI2014]力