Vue3.0 child component receives the value of the parent component and calls the method of the parent component

The parent component uses the child component and passes values ​​and methods to the child component

html:
use v-bind that is: xxx="variable/method" to pass values ​​or methods to subcomponents, define variable id and variable setIds below, and pass the value of searchForm.id and setIds method to subcomponents

<template>
	<ExpertsConfiguration 
	   :id="searchForm.id" 
	   :setIds="setIds"
	 ></ExpertsConfiguration>
 </template>

js:

import { ref,reactive,onMounted,onBeforeUnmount } from 'vue';
import ExpertsConfiguration from "../ExpertsConfiguration/ExpertsConfiguration.vue" //引用子组件
export default {
    name: "GetMyTaskWaitingPageList",
    setup() {
    	let searchForm = reactive({
            id: 1,
        })
        const setIds= () => {
			searchForm.id = 666
        }
         onMounted(() => {})
        return {
        	searchForm ,
        	setIds
        }
    },
    components: {
        ExpertsConfiguration,
    }
}

The child component receives the value of the parent component and calls the method of the parent component

js:
first receive the value from the parent component through props, and then use the first parameter props in the setup to get all the variables and methods of the parent component

import { ref,reactive,onMounted,onBeforeUnmount } from 'vue';
export default {
    nname: "ExpertsConfiguration",
    setup(props, context) {
    	//接收父组件传来的id
        let listId = ref("");
        listId.value = props.id
        const getIds= () => {
        	//props可以拿到父组件所有的变量以及方法
			if(props.setIds){
               props.setIds();//直接调用父组件方法即可
            }
        }
        onMounted(() => {})
        return {
        	listId,
        	getIds
        }
    },
    props: { //接收子组件传值
        id: Number | String,
        setIds: {
            type: Function,
            default: null
        }
    },
    components: {}
}

html:

<template>
	<div>
		{
   
   {listId}}
		<a-button type="primary" @click="getIds">点击</a-button> 
	</div>
</template>

おすすめ

転載: blog.csdn.net/Sunshinedada/article/details/128041860