首页 > 其他分享 >Vue3中操作子组件实例

Vue3中操作子组件实例

时间:2023-01-05 11:13:42浏览次数:47  
标签:INFO info vue const childDom 实例 Vue3 组件 ref

子组件Child.vue

<template>
  <hr/>
   {{INFO}}
  <hr/>
  <button @click="changeInfo">changeInfo</button>
</template>

<script setup lang="ts">
  import {ref, reactive} from "vue"
  const INFO = ref("We are the world");
  const changeInfo = () => {
    console.log(`info: ${INFO}`);
    INFO.value = "Hello World";
  }
  // 将需要暴露出去的数据和方法都可以暴露出去;
  defineExpose({
      INFO,
      changeInfo
  })
</script>

<style lang="less" scoped></style>

父组件 Parent.vue

<template>
  <Child ref="childDom"></Child>
  <button @click="clickIt">ClickIt</button>
</template>

<script setup lang='ts'>
import {ref, reactive} from "vue"
import Child from "./Child.vue"
// 子组件实例   
// Vue3中的两种写法★
// const childDom = ref(null);
const childDom = ref<HTMLElement>();
const clickIt = () => {
     // Vue2中的写法
    // let info = this.$refs.childDom.INFO;
    let info = childDom.value.INFO;
    // 执行子组件实例中的方法
    childDom.value.changeInfo();
    alert(`info: ${info}`);
}

</script>

<style lang="less" scoped></style>

标签:INFO,info,vue,const,childDom,实例,Vue3,组件,ref
From: https://www.cnblogs.com/openmind-ink/p/17026959.html

相关文章