这个系类网上的博客有很多,我就主要和大家分享一下组件通信中父子传参的用法,主要是在一天之内写两篇博客有流量券奖励,我冲了。
在vue3的Father.vue文件中,
<template>
<Son :name="name" :FatherMethods="FatherMethods"/>
</template>
<script setup>
import { ref } from 'vue'
import Son from '../views/Son.vue'
const name = ref('张三')
const FatherMethods = () =>{
console.log('我是父组件的方法')
}
</script>
<style scoped>
</style>
在vue3的Son.vue文件中,
<template>
<h2>父组件传过来的名字:{{ name }}</h2>
</template>
<script setup>
const props = defineProps({
name: String,
FatherMethods: Function
})
const callFatherMethods = () => {
props.FatherMethods()
}
</script>
<style scoped>
</ style>
前面是父传子,props(defineProps)的运用,把父组件的值和方法传给子组件,下面探讨emits(defineEmits)的用法,相当于子传父的用法。
在vue3的Father组件中,
<template>
<Son @giveMoney="giveMoney" />
</template>
<script setup>
import Son from '../views/Son.vue'
const money = ref(0)
const giveMoney = (value) =>{
money += value
}
</script>
<style scoped>
</style>
在vue3的Son组件中,
<template>
<button @click="NeedMoney"></button>
</template>
<script setup>
const emits = defineEmits(['giveMoney'])
const NeedMoney = () =>{
emits('giveMoney',500)//前面那个是调用的父组件的方法,后面那个是传给那个方法的参数
}
</script>
<style scoped>
</style>
我这里用通俗的语言解释一下emits(defineEmits)的用法,子传父的用法,就是父亲先定义好给钱函数giveMoney()在执行到儿子组件的时候@giveMoney="giveMoney"相当于把父亲组件的给钱函数传给儿子,儿子用defineEmits(['giveMoney'])去接收,此时在儿子组件中定义一个点击事件,触发要钱函数NeedMoney(),NeedMoney()触发父亲传过来的giveMoney()函数,并携带传输传给父亲,让父亲执行给钱函数giveMoney()。
可能这里和官方的解释有冲突,我只是便于记忆才这样记的,主要想帮大家记住,我刚开始学的时候记了好几次都没记住,就尝试用这种方法记忆。要是和标准不一致,不喜勿喷,狗头保命。