您的位置:首页 > 产品设计 > UI/UE

[IMWeb训练营作业]Vuejs的父子组件通信

2017-04-22 08:14 573 查看

说明

父组件通过传递prop:list等到子组件实现通信。

子组件通过emit事件将item传到父组件实现通信。

运行效果

Demo



核心代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Select</title>
<script src="vue.js"></script>
<style>
*{
margin:0;
padding: 0;
font-size: 12px;
}
.warp{
width: 200px;
margin: 10px;
padding: 10px;
border: 5px solid #cca0cc;
border-radius: 10px;
background: #ccbacc;
}
.keyWord{
box-sizing: content-box;
height: 16px;
padding: 2px;
/*border: 2px solid #bbb;*/
border-radius: 5px;
}
.keyBtn{
color:#fff;
background: #cca0cc;
box-sizing: content-box;
height: 16px;
padding: 2px;
/*border: 2px solid #bbb;*/
border-radius: 5px;
}

/* 子组件 */
.list li{
margin-top:5px;
display: block;
list-style: none;
text-decoration: none;
color:white;
height: 20px;
padding: 2px;
border-radius: 5px;
}
.list li:hover{
background: #cc88cc;
cursor:pointer;
}

body{
display: flex;
}
</style>
</head>
<body>
<div id="app">
<custom-select button-value="查询" v-bind:list="list1"></custom-select>
</div>
<div id="app2">
<custom-select button-value="搜索" v-bind:list="list2"></custom-select>
</div>
<script>
// var obj={selectShow:true}
// 注册component
Vue.component("custom-select",{
data:function(){
return {
selectShow:true,inputValue:""
}
},
props:["buttonValue","list"],
methods:{
changeValueHandle:function(item){
this.inputValue=item;
}
},
template:`<section class="warp">
<div class="searchIpt">
<div class="clearFix">
<input type="text" class="keyWord" v-bind:value="inputValue" v-on:click="selectShow=!selectShow">
<input type="button" v-bind:value="buttonValue" class="keyBtn">
<span></span>
</div>
<custom-ul v-show="!selectShow" v-bind:list="list" v-on:receive="changeValueHandle"  ></custom-ul>
</div>

</section>`
})

Vue.component("custom-ul",{
props:["list"],
template:`<ul class="list" >
<li v-for="item in list" v-on:click="selectValueHandle(item)">{{item}}</li>
</ul>`,
methods:{
selectValueHandle:function(item){
this.$emit("receive",item);
}
}
})

var data = {
list1:['今天的机票','明天的日程','还是睡觉吧'],
list2:['今天','明天','后天']
}
new Vue({
el:"#app",
data:data
})
new Vue({
el:"#app2",
data:data
})
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue-js vue javascript