父子组件通信
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="ddd">
<cpn :p1="message1"
:p2="message2"
@bn1="m1"
@bn2="m2"
></cpn>
</div>
<template id="cpn">
<div>
<input type="text" :value="n1" @input="b1">
<h2>
props:{{p1}}
</h2>
<h2>
data:{{n1}}
</h2>
<input type="text" :value="n2" @input="b2">
<h2>
props:{{p2}}
</h2>
<h2>
data:{{n2}}
</h2>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
const ddd=new Vue({
el:'#ddd',
data:{
message1:1,
message2:0
},
methods: {
m1(value){
this.message1=parseFloat(value)
},
m2(value){
this.message2=parseFloat(value)
}
},
components:{
cpn:{
template:"#cpn",
props:{
p1:Number,
p2:Number
},
data(){
return{
n1:this.p1,
n2:this.p2
}
},
methods:{
b1(event){
this.n1=event.target.value
this.$emit('bn1',this.n1)
},
b2(event){
this.n2=event.target.value
this.$emit('bn2',this.n2)
}
}
}
}
})
</script>
</body>
</html>
$children $ref
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<template id="cpn">
<div>
我是子组件
</div>
</template>
<div id='app'>
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
<cpn ref="aaa"></cpn>
<cpn></cpn>
<button @Click="showC">console</button>
</div>
<script src='../js/vue.js'></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:'hello'
},
methods: {
showC(){
// console.log(this.$children[2].m1)
alert(this.$refs.aaa.m1)
}
},
components:{
cpn:{
template:"#cpn",
data(){
return{
m1:"qqqq"
}
}
}
}
})
</script>
</body>
</html>
作用域插槽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<template id="cpn">
<div>
<slot :data="pLanguages">
<ul>
<li v-for="item in pLanguages">{{item}}</li>
</ul>
</slot>
</div>
</template>
<div id='app'>
<cpn></cpn>
<cpn>
<template slot-scope="slot">
<ul>
<span>
{{slot.data.join(' - ')}}
</span>
</ul>
</template>
</cpn>
<cpn></cpn>
</div>
<script src='../js/vue.js'></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:'hello',},
components:{
cpn:{
template:"#cpn",
data(){
return{
pLanguages: ['JavaScript', 'Python', 'Swift', 'Go', 'C++']
}
}
}
}
})
</script>
</body>
</html>