在组件中写组件,形成组件嵌套的时候,就是父子组件
父组件向子组件传值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue_父组件向子组件传值</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<comp01></comp01>
</div>
<template id='comp01'>
<div>
<h1>父组件</h1>
<input type="text" v-model="uname" />
<comp02 :uname='uname'></comp02>
</div>
</template>
<template id='comp02'>
<div>
<h3>子组件</h3>
uname:{{uname}}
</div>
</template>
<script type="text/javascript">
let comp02={
template:'#comp02',
props:['uname']
}
let comp01={
template:'#comp01',
data(){
return{
uname:'dcb'
}
},
components:{
comp02
}
}
let vm = new Vue({
el:'#app',
data:{
},
components:{
comp01
}
})
</script>
</body>
</html>
子组件的值随父组件的值变化↓
子组件给父组件传值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue_子组件给父组件传值</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<comp01></comp01>
</div>
<template id='comp01'>
<div>
<h1>{{msg}}</h1>
<h3>子组件传来的值:{{uname}}</h3>
<!-- 3、绑定子组件提供的 fromchild事件,设置接收数据的函数 -->
<comp02 @fromchild='get'></comp02>
</div>
</template>
<template id='comp02'>
<div>
<h3>{{msg}}</h3>
<input type="text" v-model="uname" />
<!-- 1、触发向父组件传值的事件 -->
<button @click="doSend()">向父组件传值</button>
</div>
</template>
<script type="text/javascript">
let comp02 = {
template:'#comp02',
data(){
return {
msg:'子组件',
uname:'tom'
}
},
methods:{
doSend(){
//2、通过$emit函数向父组件发送数据
// 参数1表示调用子组件标签的事件名,
// 参数2表示要发送的数据
this.$emit('fromchild',this.uname);
}
}
}
let comp01 = {
template:'#comp01',
data(){
return {
msg:'父组件',
uname:''
}
},
components:{
comp02
},
methods:{
//4、创建函数,通过参数接收子组件传来的值
get(a){
this.uname = a;
}
}
}
let vm = new Vue({
el:'#app',
components:{
comp01
}
})
</script>
</body>
</html>
点击向父组件传值按钮后↓