@父子组件通信 父传子:props 子传父:通过$emit发射事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父子组件通信</title>
</head>
<body>
<div id="app1">
<cpn1 :cmovies="movies"></cpn1>
</div>
<template id="myCpn1">
<div>
<ul>
<li v-for="item in cmovies">{{item}}</li>
</ul>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app1 = new Vue({
el:'#app1',
data:{
message:'hello vue',
movies:['速度与激情','海王','疯狂动物城']
},
components:{
cpn1:{
template:'#myCpn1',
props:{
cmovies:{
type:Array,
default(){
return[]
}
}
}
}
},
})
</script>
<div id="app2">
<cpn2 @item-click="cpnClick"></cpn2>
</div>
<template id="myCpn2">
<div>
<button v-for="item in newtempdata"
@click="btnClick(item)">
{{item.name}}
</button>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const app2 = new Vue({
el:'#app2',
data:{
message:'hello vue',
},
components:{
cpn2:{
template:'#myCpn2',
data(){
return{
newtempdata:[
{id:'aa',name:'鸿星尔克'},
{id:'bb',name:'安踏'},
{id:'cc',name:'361'},
{id:'dd',name:'李宁'},
]
}
},
methods:{
btnClick(item){
this.$emit('item-click',item)
}
},
},
},
methods:{
cpnClick(item){
console.log('cpnClick')
}
}
})
</script>
</body>
</html>
点击按钮后Console:
|