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>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐