16、Vue 3 (2024 版)基础笔记 - props 通过函数实现子传父数据

作者: 温新

图书: 【Vue 3 setup 使用实记】

阅读: 67

时间: 2024-05-19 01:28:33

本篇文章,我们通过事件的方式,实现子传父。

1、子组件

src/components/comp/SearchComp.vue

<template>
    搜索:<input type="text" v-model="searchValue" >
    <p>{{ onSearch(searchValue) }}</p>
</template>

<script setup lang="ts">
    import { ref } from 'vue';
    
    const searchValue = ref('')
    const props = defineProps(['onSearch'])
</script>
2、父组件

src/App.vue

<template>
    <p>子组件中的搜索内容:{{ search }}</p>
    <SearchComp :onSearch="getSearchValue"/>
</template>

<script setup lang="ts">
    import { ref } from "vue";
    import SearchComp from "./components/comp/SearchComp.vue";

    const search = ref('')

    const getSearchValue = (data:string) => {
        search.value = data
    }
</script>

使用 props 进行组件数据传递时,事件是自动触发的。

请登录后再评论