在Vue3中,可以通过ref来获取子组件实例,然后调用子组件的方法。具体步骤如下:

  1. 在子组件中,使用ref来获取子组件实例:

import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  setup() {
    const childComponentRef = ref(null)

    const triggerChildMethod = () => {
      childComponentRef.value.childMethod()
    }

    return {
      childComponentRef,
      triggerChildMethod
    }
  }
}

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
  data() {
    return {
      message: 'Hello from child component!'
    }
  },
  methods: {
    childMethod() {
      console.log('Child method called!')
    }
  }
}
</script>

2.在父组件中,使用ref来获取子组件实例,并定义一个方法来触发子组件的方法:

<template>
  <div>
    <ChildComponent ref="childComponentRef" />
    <button @click="triggerChildMethod">Trigger child method</button>
  </div>
</template>

<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  setup() {
    const childComponentRef = ref(null)

    const triggerChildMethod = () => {
      childComponentRef.value.childMethod()
    }

    return {
      childComponentRef,
      triggerChildMethod
    }
  }
}
</script>

3。在父组件中,使用ref来获取子组件实例,并在setup函数中定义一个方法来触发子组件的方法。然后在模板中绑定一个按钮,当点击按钮时,调用triggerChildMethod方法来触发子组件的方法:

<template>
  <div>
    <ChildComponent ref="childComponentRef" />
    <button @click="triggerChildMethod">Trigger child method</button>
  </div>
</template>

<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  setup() {
    const childComponentRef = ref(null)

    const triggerChildMethod = () => {
      childComponentRef.value.childMethod()
    }

    return {
      childComponentRef,
      triggerChildMethod
    }
  }
}
</script>

或者子组件用 defineExpose用法

 
 
<script setup>
import { ref } from 'vue';
    const demo=ref('测试用例')
    const  handleVal=()=>{
        demo.value="已改变"
    }
//将需要暴露出去的数据与方法都可以暴露出去
    defineExpose({
        demo,
        handleVal,
    })
</script>
<template>
  <div class="inner">
      {{demo}}
      <button @click="handleVal">改值</button>
  </div>
</template>
<style lang="scss" scoped>
 
</style>

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐