vue3中ref获取子组件的值代码示例
更新时间:2023年08月16日 10:06:14 作者:我的代码永没有bug
这篇文章主要给大家介绍了关于vue3中ref获取子组件值的相关资料,在Vue3中父组件获取子组件的值可以通过使用'ref'和'$refs'来实现,文中通过代码示例介绍的非常详细,需要的朋友可以参考下
一、< script setup >通过ref获取子组件的值或方法
父组件:
<pane-account ref="accountRef"></pane-account> <script lang="ts" setup> import { ref } from 'vue'; import PaneAccount from './pane-account.vue'; const accountRef = ref<InstanceType<typeof PaneAccount>>(); const loginAction = () => { // 父组件获取子组件ref值 accountRef.value?.accountLoginAction(); }; </script>
子组件:
<script lang="ts" setup> import { ref, reactive, defineProps, defineExpose } from 'vue'; import type { ElForm } from 'element-plus'; const formRef = ref<InstanceType<typeof ElForm>>(); const accountLoginAction = () => { formRef.value?.validate((valid) => { if (valid) { console.log('登录'); } else { console.log('222'); } }); }; // 只有defineExpose暴露的值或方法才能被父组件通过ref访问 defineExpose({ accountLoginAction });
二、setup()通过ref获取子组件值
父组件:
<pane-account ref="accountRef"></pane-account> <script lang="ts"> import { defineComponent, reactive, ref } from 'vue' export default defineComponent({ setup() { const accountRef = ref<InstanceType<typeof LoginAccount>>() const loginAction = () => { accountRef.value?.accountLoginAction() } return { loginAction, accountRef } } }) </script>
子组件:
<script lang="ts"> import { defineComponent, PropType, computed, ref } from 'vue' export default defineComponent({ setup(props, { emit }) { const accountLoginAction = () => { console.log('子组件的方法') } return { accountLoginAction } } }) </script>
总结
到此这篇关于vue3中ref获取子组件的值的文章就介绍到这了,更多相关vue3 ref获取子组件值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
element-ui table使用type='selection'复选框全禁用(全选禁用)详解
element-ui中的table的多选很好用,但是如果其中某一项禁止选择,该怎样操作呢,下面这篇文章主要给大家介绍了关于element-ui table使用type='selection'复选框全禁用(全选禁用)的相关资料,需要的朋友可以参考下2023-01-01详解vue2.0的Element UI的表格table列时间戳格式化
本篇文章主要介绍了详解vue2.0的Element UI的表格table列时间戳格式化,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2017-06-06
最新评论