Vue 子组件向父组件传递数据的三种方式

13,149 阅读1分钟

Vue 子组件向父组件传递数据的三种方式

1. 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on)

父组件:父组件通过绑定自定义事件,接受子组件传递过来的参数

<template>
   <div class="parent">
     <p>父组件接手到的内容:{{ username }}</p>
     <Son  @transfer="getUser"></Son> 
      <!-- 监听子组件触发的transfer事件,然后调用getUser方法 -->
   </div>
 </template>
 <script>
 import son from './Son'
 export default {
   name: 'HelloWorld',
   data () {
     return {
       msg: '父组件',
       username:'',
     }
   },
   components:{son},
   methods:{
     getUser(msg){
       this.username= msg
     }
   }
 }
 </script>

子组件:子组件通过$emit触发父组件上的自定义事件,发送参数

 <template>
   <div class="son">
     <button @click="setUser">传值</button>
   </div>
 </template>
 <script>
 export default {
   name: "son",
   data(){
     return {
       user:'子传父的内容'
     }
   },
   methods:{
     setUser:function(){
       this.$emit('transfer',this.user)//触发transfer方法,this.user 为向父组件传递的数据
     }
   }
 }
 </script>

2.通过父组件给子组件传递函数类型的props实现:子给父传递数据

父组件:  
<SchoolCm :getSchoolName="getSchoolName"></SchoolCm>
methods: {  
     getSchoolName(name) {
        console.log('接受到子组件传来的数据:', name)
    }
}
子组件:  
<button @click="sendSchoolName">把学校名给App</button>  
 props: ['getSchoolName'], 
 data(){
   return {
     name:"子传给父的内容"
 }}
 methods: {
      sendSchoolName() {
        this.getSchoolName(this.name)
      }
}

3.通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref)

   说明:这种方式虽然麻烦,但是更灵活,可以使用setTimeout控制响应时间。

父组件:  
<StudentCm name="李四" ref="student"></StudentCm>  
 mounted(){
      setTimeout(() =>{
        // 函数体
        this.$refs.student.$on('wxj', this.getStudentName)
      }, 3000)
},  
methods: {  
    getStudentName(name) {
        console.log('接受到了子组件传来的数据:', name)
     }
}
子组件:  
<button @click="sendStudentName">把学生名给App</button>  
methods: {
sendStudentName() {
   // 触发Student组件实例身上的wxj事件
   this.$emit('wxj')
    }

}