vue父子组件的三种传值方式
-
函数类型的props传值
//父组件 <template> <Children :getChildName="getChildName" /> </tempalte> <script> export default { name:"Father", data(){ return{ } }, methods:{ getChildName(name){ console.log("父组件接受到Children的名字",name) } } } </script>
//子组件 <template> <div> <button @click="sendChildName">prop向父组件传值</button> </div> </tempalte> <script> export default { name:"Children", props:["getChildName"], data(){ return{ name:"小明" } }, methods:{ sendChildName(){ this.getChildName(this.name) } } } </script>
-
通过自定义事件传值
//父组件中 <Student @getStudent="getStudentName" />
method:{ getStudentName(){ console.log("父组件接受到Student的名字",name) } }
//子组件中 <template> <button @click="sendStudentName">把Student名字给父组件</button> </tempalte> <script> export default { data(){ reutrn{ name:"张三" } }, method:{ sendStudentName(){ this.$emit("getStudent",this.name) } } }
-
通过ref属性为子组件绑定事件
//父组件中 <Student ref="student" /> <script> export default { mounted(){ this.$refs.student.$on('getStudent',this.sendStudentName) }, method:{ getStudentName(){ console.log("父组件接受到Student的名字",name) } } } </script>
//子组件中 <template> <button @click="sendStudentName">把Student名字给父组件</button> </tempalte> <script> export default { data(){ reutrn{ name:"张三" } }, method:{ sendStudentName(){ this.$emit("getStudent",this.name) } } }