1、父向子
在子组件上自定义一个属性,属性名随意 ,属性值是你要传的参数。
<template>
<div class="home">
<HelloWorld :index="num" /> //子组件
</div>
</template>
然后在子组件代码script标签中,导入definePops 这个方法,定义一个常量props用来接收父组件传过来的值,就可以了。
<script setup>
import {ref ,defineProps} from "vue";
const props = defineProps({
index:{}
}
</script>
<template>
<div class="hello">
<h2>{{ index }}</h2>
</div>
</template>
2、子向父
在子组件声明一个任意常量,用于定义传输参数的方法,名字自定义。
const emit = defineEmits(["updateNum"]);
同时在子组件中定义一个方法去触发emit这个方法,
emit('updateNum',value) //value是传给父元素事件的参数
父组件中子组件标签上加一个方法,调用方法参数就是子组件传给父组件的参数
<template>
<div class="home">
<HelloWorld @undataNum='getNum' :index="num" />
</div>
</template>
<script>
const getNum =(value)=>{
console.log(value);//value为传过来的参数
}
</script>
子向父还有一种方法
在子组件中导入defineExpose方法,把你想要传的参数抛出去
<script setup>
import { ref, defineProps, inject, defineExpose } from "vue";
const numPlus = ref(1);
defineExpose({ numPlus});
</script>
在父组件中子组件的标签上接收ref,名字自定义
<HelloWorld :index="num" ref="treeRef" />
然后再页面直接打印就可以了
console.log(treeRef.value.numPlus);