props + $emit 实现父子组件传值
例子要求:
通过例子要求我们可以分析出: 三个组件
- 主组件(父组件–展示个人信息列表~)
- 新增子组件(子组件–填写数据、新增用户)
- 详情子组件(子组件–查看点击的当前用户的个人信息详情)
既然有父子组件,那么他们其中必然需要联系,这时候 props、$emit 就派上用场了!!!
在这之前:如果你还不了解props
、$emit
、$parent
,你可以先看看下面的博客,理解后再看本篇文章:
实现效果(这使用了 boostrap 简单布局)
首页
点击新增用户
默认页面
可以在表单输入数据~~
当点击新增时,则会新增用户,返回主页面,这时候,主页面会展示刚刚新增的用户~~
当点击取消不会新增用户~~,还是原始页面(1条数据)
点击详情
可以查看到刚刚新增的用户信息~
点击返回,则返回主页面~~
点击删除
会删除选中的项~比如删除第一项–蔡徐坤,则白胡子为第一项了
文件目录如下
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>个人信息展示2</title>
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-3.3.7-dist/js/bootstrap.min.js">
<script src="./vue.js"></script>
<style>
.father {
width: 375px;
height: 667px;
border: 1px solid palevioletred;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
display: flex;
flex-direction: column;
}
.father-page {
margin: 10px 10px;
}
.father .father-form {
margin: 10px 0;
display: flex;
}
.father .father-form table {
text-align: center;
}
.child-addPage {
margin: 10px 10px;
}
.item-flex {
/* 水平居中 */
display: flex;
justify-content: center;
}
.child-detailPage{
margin: 10px 10px;
}
.text-center{
text-align: center;
}
</style>
</head>
<body>
<!--父组件-->
<div id="app" class="father">
<div class="father-page" v-if="showMain">
<div class="father-add">
<button type="button" class="btn btn-primary" @click="showAddPage">新增用户</button>
</div>
<div class