これは、対応するサブ要素を取得し、サブ要素内のメソッドを呼び出すために vue2
使用されます 。ref
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 () {}
で使用され 、 ref
子要素を取得してメソッドを呼び出す方法:
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>
子要素を取得 し、メソッドを呼び出す ref
方法
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() }) |