vue父子之间传值

1.父组件向子组件传值

定义父子组件 并在父组件中引入注册子组件

< template >
< div >
< child v-bind:greetMsg=" name" ></ child >
</ div >
</ template >
< script >
import Child from '../components/child.vue'
export default {
data(){
return {
name: "你好,我是爸爸"
}
},
components:{
Child
}
}
</ script >
< style >
</ style >

定义子组件

< template >
< div >{{ greetMsg}} </ div >
</ template >
< script >
export default {
props:[
'greetMsg'
]
}
</ script >
< style >
</ style >

页面显示效果是

父组件向子组件传值是利用props

子组件中的注意事项:props:['greetMsg'],注意props后面是[]数组可以接收多个值,不是{}。

                                且此处的greetMsg用greet-msg会报错,记住需用驼峰法命名

父组件中的注意事项:数据是在父组件中定义

                                需先引入再注册Child

                                 使用的是v-bind:greetMsg="name",此处的greetMsg需与子组件中props中的一致

2.子组件向父组件传值

定义父组件

< template >
< div >
< child v-on:send=" getMessage" ></ child >
< div >{{ msg}} </ div >
</ div >
</ template >
< script >
import Child from '../components/child'
export default {
components:{
Child
},
data(){
return {
msg: ''
}
},
methods:{
getMessage( greetMsg){
this. msg= greetMsg
}
}
}
</ script >
< style >
</ style >

定义子组件

< template >
< div >
< button @click=" sendMessage" >点击一下,向父组件传值 </ button >
</ div >
</ template >
< script >
export default {
data(){
return{
sayName: "您好,我叫小明,我是您孩子"
}
},
methods:{
sendMessage(){
this. $emit( 'send', this. sayName)
}
}
}
</ script >
< style >
</ style >

点击按钮后,页面显示结果是

子组件向父组件传值是利用在子组件中使用$emit在父组件中绑定事件来实现

子组件中的注意事项:需在子组件中定义数据

                                 绑定事件,比如@click事件,再在methods里面定义该事件this.$emit('send',this.sayName)

父组件中的注意事项:引入注册子组件

                                 绑定相应的方法 v-on:send注意此处的send需与子组件中的this.$emit()中的第一个参数一致,记住需使用驼峰法命名

                                  


                 

猜你喜欢

转载自blog.csdn.net/xiaoxiaoluckylucky/article/details/79584893