vue3父組件方法之間方法的互相調用


場景描述

在項目開發中。我們可能會使用父組件調用子組件中的方法
也有可能子組件中調用父組件中的方法
下面我們來看一看組件之間方法的調用

父組件頁面

<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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM