一、< 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>
文章来源地址https://www.toymoban.com/news/detail-560836.html
文章来源:https://www.toymoban.com/news/detail-560836.html
到了这里,关于vue3中ref获取子组件的值的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!