父组件:
<template>
<div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
<h3>我是父组件</h3>
<div>子组件向父组件传递的值:</div>
<Child :FatherMsg="msg"></Child>
</div>
</template>
<script>
import Child from './Child';
export default {
components: {
Child
}
}
</script>
子组件:
<template>
<div style="border:1px solid black;width:400px; height: 130px;">
<h3>我是子组件</h3>
<button>子组件将值传递给父组件</button>
<!--第二步:直接引用-->
<div>子组件接收父组件的值:{{FatherMsg}}</div>
</div>
</template>
父向子传值:
实现思路:子组件通过 props 来接受父组件传过来的值。
先在父组件中引入子组件
<template>
<div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
<h3>我是父组件</h3>
<div>子组件向父组件传递的值:</div>
<!--第三步:使用子组件-->
<!--第五步:绑定msg变量-->
<Child :FatherMsg="msg"></Child>
</div>
</template>
<script>
//第一步:引用子组件
import Child from './Child';
export default {
data(){
return{
//第四步:规定msg变量
msg:'I am your father'
}
},
//第二步:注册子组件
components: {
Child
}
}
</script>
接着在子组件里通过 props 来接收,这样子组件就接收到了父组件传递过来的值了。
<template>
<div style="border:1px solid black;width:400px; height: 130px;">
<h3>我是子组件</h3>
<button>子组件将值传递给父组件</button>
<!--第二步:直接引用-->
<div>子组件接收父组件的值:{{FatherMsg}}</div>
</div>
</template>
<script>
export default {
data() {
return {
data: 'I am your children',
}
},
//父向子传第一步,使用props接收,规定父组件传来的值被FatherMsg变量接收
props: ['FatherMsg']
}
</script>
子向父传值:
实现思路,逆向传值,使用$emit来传值
在子组件中给 button 按钮添加 click 事件,来通过 this.$emit 自定义事件,并传入一个参数:
<template>
<div style="border:1px solid black;width:400px; height: 130px;">
<h3>我是子组件</h3>
<!--子向父传第一步:规定点击事件,触发方法传值-->.
<button @click="send">子组件将值传递给父组件</button>
<!--父向子传第二步:直接引用-->
<div>子组件接收父组件的值:{{FatherMsg}}</div>
</div>
</template>
<script>
export default {
data() {
return {
childM: 'I am your children',
}
},
//父向子传第一步,使用props接收,规定FatherMsg变量
props: ['FatherMsg'],
methods:{
send(){
//子向父传第二步,使用$emit来向父组件逆向传值,ListenChild为父组件中的方法,this.childM为要给父组件传过去的值
this.$emit('ListenChild', this.childM);
}
},
}
</script>
在父组件中的子组件标签里,先在 data 里定义一个变量接收这个值,然后监听在监听子组件中引用的父组件的自定义事件,并接受这个参数赋值给定义的变量:
<template>
<div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
<h3>我是父组件</h3>
<!--子向父传第四步,使用{{}}来展示-->
<div>子组件向父组件传递的值:{{childMsg}}</div>
<!--父向子传第三步:使用子组件-->
<Child :FatherMsg="msg"></Child>
<!--子向父传第一步,监听子组件向上散发的事件,绑定自己的方法-->
<Child @ListenChild="Listen"></Child>
</div>
</template>
<script>
//父向子传第一步:引用子组件
import Child from './Child';
export default {
data(){
return{
msg:'I am your father',
//子向父传值:第三步,规定变量,定义接收子组件传来的值
childMsg:'',
}
},
//父向子传第二步:注册子组件
components: {
Child
},
methods:{
//子向父传值:第二步在父组件中规定方法,用来接收子组件传来的值
Listen(childM){
console.log(childM)
this.childMsg=childM;
}
}
}
</script>