Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

vue3 父组件通过ref 访问子组件

  1. User

    vue3 父组件通过ref 访问子组件

  2. Assistant

    在 Vue 3 中,可以通过 ref 和 $refs 访问子组件。

    首先,在子组件中使用 defineExpose 方法暴露一些内部属性或方法:

    // 子组件 MyChild.vue
    <script>
    export default {
      name: "MyChild",
      data() {
        return {
          message: "Hello from child component",
        };
      },
      methods: {
        sayHello() {
          console.log("Hello from child component method");
        },
      },
      // 在组件中暴露实例属性和方法
      defineExpose: ["message", "sayHello"],
    };
    </script>
    

    然后,在父组件中使用 ref 获取子组件实例,并通过 $refs 访问其暴露的属性和方法:

    // 父组件 MyParent.vue
    <template>
      <div>
        <MyChild ref="myChildRef" />
        <button @click="handleClick">调用子组件方法</button>
      </div>
    </template>
    <script>
    import { ref } from "vue";
    import MyChild from "./MyChild.vue";
    
    export default {
      name: "MyParent",
      components: {
        MyChild,
      },
      setup() {
        const myChildRef = ref(null);
    
        const handleClick = () => {
          console.log(myChildRef.value.message);
          myChildRef.value.sayHello();
        };
    
        return {
          myChildRef,
          handleClick,
        };
      },
    };
    </script>
    

    注意,在 Vue 3 中,$refs 在模板中访问时需要加上 .value,在 setup 函数中则直接访问即可。同时也要注意,ref 返回的是一个响应式对象,需要使用 .value 来获取其实际值。

  3. User

    父组件通过ref获取子组件dom

  4. Assistant

    在 Vue 3 中,可以通过 ref 和 $el 访问子组件的 DOM 元素。

    首先,在子组件中使用 ref 给子组件的根元素命名:

    // 子组件 MyChild.vue
    <template>
      <div class="my-child" ref="myChildRef">
        <h1>Hello from child component</h1>
      </div>
    </template>
    

    然后,在父组件中使用 ref 获取子组件实例,并通过 $el 访问其根元素:

    // 父组件 MyParent.vue
    <template>
      <div>
        <MyChild ref="myChildRef" />
        <button @click="handleClick">获取子组件 DOM</button>
      </div>
    </template>
    <script>
    import { ref } from "vue";
    import MyChild from "./MyChild.vue";
    
    export default {
      name: "MyParent",
      components: {
        MyChild,
      },
      setup() {
        const myChildRef = ref(null);
    
        const handleClick = () => {
          console.log(myChildRef.value.$el);
        };
    
        return {
          myChildRef,
          handleClick,
        };
      },
    };
    </script>
    

    注意,在 Vue 3 中,$el 已经不是响应式的了,所以不需要使用 .value。而且,如果子组件的根元素没有使用 ref 命名,可能会出现 $el 为 undefined 的问题,需要确保子组件的根元素使用了 ref 命名。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.