父传子
父组件 FatherComponent.vue
父组件中有一个parentData 值为 ‘父组件数据’
<!-- 父组件 -->
<template>
<div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const parentData = ref('父组件数据');
</script>
子组件 ChildComponent.vue
想要在子组件中显示父组件的 parentData
<!-- 子组件 -->
<template>
<div>我是子组件,这是父组件的值:</div>
</template>
<script setup>
</script>
首先将子组件引入父组件,这是父组件中就会显示子组件里的内容
<!-- 父组件 -->
<template>
<ChildComponent />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentData = ref('父组件数据');
</script>
然后在父组件中设置传递子组件的参数,在<ChildComponent />子组件标签中用冒号绑定一个值,:parentData 是子组件接收数据的变量名,等号后面的 parentData 是父组件的参数
<!-- 父组件 -->
<template>
<ChildComponent :parentData="parentData" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentData = ref('父组件数据');
</script>
父组件要做的已经完成,下面看子组件,目前父组件已经将 const parentData = ref('父组件数据');
这一变量传递给了子组件,现在需要子组件进行接收
使用 defineProps 进行接收,接受方法如下:
<!-- 子组件 -->
<template>
<div>我是子组件,这是父组件的值:{{ parentData }}</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
parentData: String
});
</script>
这样就是父组件向子组件传递参数的方法
子传父
子传父需要用到 defineEmits 去向父组件传参,使用方法如下:
首先子组件需要使用 defineEmits ,并且填写要传递的子组件参数
<!-- 子组件 -->
<template>
<div>我是子组件</div>
</template>
<script setup>
import { defineEmits } from 'vue';
const value = '子组件参数'
const childEmit = defineEmits(["childValue"]);
//使用childEmit传递参数
childEmit('childValue',value )
</script>
然后父组件需要接收子组件的参数,通过@来绑定一个函数即可,函数的回调就是子组件的参数
需要注意的是父组件@所绑定的方法要与子组件一致
<!-- 父组件 -->
<template>
<ChildComponent @childValue="getChild" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const getChild = (val)=>{
console.log('接收的子组件参数:',val)
}
</script>
以上就是父子组件传参的方法
ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ ዽ ጿ ኈ ቼ