下面演示均为使用 setup 语法糖的情况!
下面演示为使用 setup 语法糖的情况,值得注意的是子组件需要使用 defineExpose 对外暴露方法,父组件才可以调用!
<template> </template> <script setup lang="ts"> // 第一步:定义子组件里面的方法 const doSth = (str: string) => { console.log("子组件的 doSth 方法执行了!" + str); } // 第二步:暴露方法 defineExpose({ doSth }) </script> <style scoped> </style>
<template> <button @click="getChild">触发子组件方法</button> <!-- 第一步:定义 ref --> <HelloWorld ref="childRef" /> </template> <script setup lang="ts"> // 一、导入 import { ref } from 'vue'; import HelloWorld from './components/HelloWorld.vue'; // 二、数据 // 第二步:定义与 ref 同名变量 const childRef = ref<any>(); // 三、函数 const getChild = () => { // 第三步: 调用子组件的方法或者变量,通过value childRef.value.doSth("随便传值!"); } </script> <style> </style>
defineExpose
使用 <script setup>
的组件是默认关闭的,也即通过模板 ref 或者 $parent
链获取到的组件的公开实例,不会暴露任何在 <script setup>
中声明的绑定。
为了在 <script setup>
组件中明确要暴露出去的属性,使用 defineExpose
编译器宏:
<script setup> import { ref } from 'vue' const a = 1 const b = ref(2) defineExpose({ a, b }) </script>
当父组件通过模板 ref 的方式获取到当前组件的实例,获取到的实例会像这样 { a: number, b: number }
(ref 会和在普通实例中一样被自动解包)。
<template> </template> <script setup lang="ts"> import { onMounted } from "@vue/runtime-core"; const emit = defineEmits([ "doSth" ]); const doSth = () => { emit('doSth'); } onMounted(() => { doSth(); }); </script> <style scoped> </style>
<template> <!-- 第一步:使用 @do-sth 或 @doSth 接受方法 --> <HelloWorld @doSth="sayHello" /> </template> <script setup lang="ts"> // 一、导入 import HelloWorld from './components/HelloWorld.vue'; // 二、函数 // 第二步: 自定义方法 const sayHello = () => { console.log("hello world!"); } </script> <style> </style>
defineProps
和 defineEmits
在 <script setup>
中必须使用 defineProps
和 defineEmits
API 来声明 props
和 emits
,它们具备完整的类型推断并且在 <script setup>
中是直接可用的:
<script setup> const props = defineProps({ foo: String }) const emit = defineEmits(['change', 'delete']) // setup code </script>
如果使用了 Typescript,使用纯类型声明来声明 prop 和 emits 也是可以的。
到此这篇关于Vue3父子组件互调方法的实现的文章就介绍到这了,更多相关Vue3父子组件互调内容请搜索源码搜藏网以前的文章或继续浏览下面的相关文章希望大家以后多多支持源码搜藏网!
【JQ】无限滚动条-jquery.infinitescroll.j
query多选下拉框插件 jquery-multiselect(
手机站jQuery自动完成插件autoComplete.js
热门源码