場景描述
在項目開發中。我們可能會使用父組件調用子組件中的方法
也有可能子組件中調用父組件中的方法
下面我們來看一看組件之間方法的調用
父組件頁面
<template>
<div>
<list-com ref="listRef"></list-com>
<button @click="changeValue" >改變值</button>
</div>
</template>
<script>
import listCom from "@/components/list-com.vue"
import { ref } from '@vue/reactivity'
export default {
components:{
listCom
},
setup () {
let listRef=ref()
function changeValue(){
// 需要注意let listRef=ref() 不能夠寫在這個函數體內,
// 否者listRef 將會找不到,因為有函數作用域
listRef.value.fatherMess([{name:'楊洋'}])
}
return {changeValue,listRef}
}
}
</script>
子組件頁面
<template>
<div>
<h2>我是子組件</h2>
兒子接受到的數據:{{ list.arr}}
</div>
</template>
<script>
import { reactive } from '@vue/reactivity';
export default {
setup () {
let list=reactive({
arr:[]
})
function fatherMess(mess){
console.log('父組件給子組件的值',mess );
list.arr=mess
}
// 雖然頁面上沒有使用這個函數,
// 但是也要拋出去,否者父組件會報錯 fatherMess is not a function
return {fatherMess,list}
}
}
</script>

出現 Uncaught TypeError: listRef.value.fatherMess is not a function 如何解決
出現這樣的錯誤,是因為子組件中的事件 fatherMess函數。
並沒有拋出出去哈
解決辦法 子組件中 return {fatherMess}

子組件調用父組件中的方法
子組件
<template>
<div>
<h2>我是子組件</h2>
<button @click="getHander" >獲取值</button>
</div>
</template>
<script>
import { reactive } from '@vue/reactivity';
export default {
setup (props,{attrs,slots,emit}) {
function getHander(){
// 不能夠在使用原來的 this.$partent.xxx()這種方式了
emit('myclick','給父組件的值' )
}
return {getHander}
}
}
</script>
父組件
<template>
<div>
<list-com @myclick="myclick"></list-com>
</div>
</template>
<script>
import listCom from "@/components/list-com.vue"
export default {
components:{
listCom
},
setup () {
function myclick(mess){
console.log(mess);
}
return {myclick}
}
}
</script>
