vue3 - Ts - 组件交互

父组件

  

<template>
  <main>
    <TheWelcome :msg="1" @change="ischange" ref="childRef" />
  </main>
</template>
<script setup lang="ts">
import { getCurrentInstance } from "@vue/runtime-core";
import TheWelcome from "../components/TheWelcome.vue";
import { ref, onMounted } from "vue";
const ischange = (e: string) => {
 console.log('子组件调用-emit');
};
const { proxy } = getCurrentInstance();
const iSref = getCurrentInstance();
let childRef = ref();
onMounted(() => {
    //调用子组件的方式(类似Vue2的 this.$ref)
   proxy.$refs.childRef.getList()
   iSref.ctx.$refs.childRef.getList()
   childRef.value.getList()
});
</script>

子组件

<script setup lang="ts">
// 接收到的父组件传递过来的数据
const props = defineProps({
  msg: [String, Boolean, Number],
  bar: Number,
});
console.log(props,'父组件传过来的参数')
const emit = defineEmits(["change", "update"]);// $emit 暴露可调用的方法
const change = (e: string) => {
  emit("change", e);
};
const getList = async () => {
  console.log("父组件调用");
};
// 暴露给父组件调用
defineExpose({
  getList
})
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容