vue2
É usado para obter ref
o subelemento correspondente e, em seguida, chamar o método dentro do subelemento.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<template> <!-- 子组件 --> <TestComponent ref= "TestComponent" ></TestComponent> </template> <script> // 导入子组件 import TestComponent from './TestComponent' export default {
components: {
TestComponent }, mounted () {
// 调用子组件方法 this .$refs.TestComponent.show() } } </script> |
Vue3
setup () {}
Usado em como ref
obter o elemento filho e chamar o método:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<template> <!-- 子组件 --> <TestComponent ref= "RefTestComponent" ></TestComponent> </template> <script> // 导入子组件 import TestComponent from './TestComponent' import { ref } from 'vue' import { nextTick } from 'process' export default {
components: {
TestComponent }, setup () {
// 定义一个对象关联上子组件的 ref 值(注意:这里的属性名必须跟子组件定义的 ref 值一模一样,否者会关联失效) const RefTestComponent = ref( null ) // 延迟使用,因为还没有返回跟挂载 nextTick(() => {
RefTestComponent.value.show() }) // 返回 return {
RefTestComponent } } } </script> |
Vue3
<script setup>
Usado em , ref
como obter o subelemento e chamar o método
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<template> <!-- 子组件 --> <TestComponent ref= "RefTestComponent" ></TestComponent> </template> <script setup> // 导入子组件 import TestComponent from './TestComponent' import { ref } from 'vue' import { nextTick } from 'process' // 定义一个对象关联上子组件的 ref 值(注意:这里的属性名必须跟子组件定义的 ref 值一模一样,否者会关联失效) const RefTestComponent = ref( null ) // 延迟使用,因为还没挂载 nextTick(() => {
RefTestComponent.value.show() }) |