子组件传递数据给父组件的三种方法
1.props
<template> <!-- App.vue --> <div id="app"> <!-- 向子组件中传入函数 --> <Student :receive="receive"></Student> </div> </template> <script> import Student from './components/Student.vue' export default { name: 'App', components: { Student }, methods: { receive(name){ console.log(name); } }, } </script>
<template> <div> <h2>{{name}}</h2> <h2>{{age}}</h2> <button @click="giveName">点我传递姓名</button> </div> </template> <script> export default { name:'Student', props:['receive'], data(){ return{ name:'张三', age:18 } }, methods:{ giveName(){ // 调用传入的函数,将name传递给父组件 this.receive(this.name) } } } </script>
2.ref
<template> <!-- App.vue --> <div id="app"> <!-- Student组件绑定自定义事件 --> <Student ref="student"></Student> </div> </template> <script> import Student from './components/Student.vue' export default { name: 'App', components: { Student }, methods: { getStudentName(name){ console.log(name); } }, mounted() { // ref绑定自定义事件 this.$refs.student.$on('getName',this.getStudentName) }, } </script>
<template> <div> <h2>{{name}}</h2> <h2>{{age}}</h2> <button @click="giveName">点我传递姓名</button> </div> </template> <script> export default { name:'Student', props:['receive'], data(){ return{ name:'张三', age:18 } }, methods:{ giveName(){ // 调用自定义事件,传入参数 this.$emit('getName',this.name) } } } </script>