vue3父子組件傳值
父組件向子組件傳值
父組件通過v-bind綁定一個數據,然后子組件通過props接受傳過來的值,跟vue2父子組件傳值差不多
father.vue
<template>
<div>
<Son :father="father" />
</div>
</template>
<script>
import { ref } from '@vue/reactivity'
import Son from './Son.vue'
export default {
components: {
Son
},
setup () {
const father = ref('我是父組件我要在子組件顯示')
return {
father
}
}
}
</script>
son.vue
<template>
<div class="son">{{father}}</div>
</template>
<script>
export default {
props: [
'father'
],
setup (props, context) {
console.log(props)
}
}
</script>
即使setup里有props參數,上面也要通過props接受一下,否則接收不到數據,props為空
子組件向父組件傳值
先在子組件里setup參數里的context里的emit解構出來然后通過emit向父組件傳值
用法同vue2的$emit一樣
<template>
<div class="son">{{father}}</div>
</template>
<script>
import { ref } from '@vue/reactivity'
export default {
props: [
'father'
],
setup (props, { emit }) {
console.log(props)
const son = ref('我是兒子要在巴巴里顯示')
emit('aa', son)
return {
son
}
}
}
</script>
父組件里通過一個自定義事件接收子組件傳過來的值
<template>
<div>
<Son @aa="write" :father="father" />
</div>
</template>
<script>
import { ref } from '@vue/reactivity'
import Son from './Son.vue'
export default {
components: {
Son
},
setup () {
const write = (e) => {
console.log(e.value)
}
const father = ref('我是父組件我要在子組件顯示')
return {
father,
write
}
}
}
</script>