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>
标签:methods,default,传递数据,export,Student,组件,给父,receive,name From: https://www.cnblogs.com/amujoe/p/17286395.html