子組件調用父組件的方法


1、通過父組件向子組件傳Function類型的參數的形式

1.1、父組件向子組件傳參的相關代碼

methods: {
    addComment (comment) {
      // unshift向數組的開始位置插入元素
      this.comments.unshift(comment)
    }
}

 

<!--父組件向子組件傳Function類型的參數-->
<add :addComment="addComment"></add>

1.2、子組件接收父組件Function類型的傳參並調用該Function

<script>
export default {
  // 通過屬性名或者屬性名和屬性類型的方式都可以接收Function類型的傳參
  // props: ['addComment'],
  props: {
    addComment: Function
  },
  data () {
    return {
      name: null,
      content: null
    }
  },
  methods: {
    addFunc () {
      // 在子組件中調用父組件的Function類型的傳參
      this.addComment({name: this.name, content: this.content})
    }
  }
}
</script>

2、通過在父組件中為子組件綁定父組件的方法的形式

2.1、在父組件中為子組件綁定父組件的方法相關代碼

methods: {
    addComment (comment) {
      // unshift向數組的開始位置插入元素
      this.comments.unshift(comment)
    }
}
<!--在父組件中給子組件綁定父組件的方法-->
<add @addComment="addComment"></add>

2.2、在子組件中調用為子組件綁定的父組件的方法

methods: {
    addFunc () {
      // 在子組件中調用父組件的為子組件綁定的方法
      this.$emit('addComment', {name: this.name, content: this.content})
    }
}

3、在父組件中通過$on為子組件綁定父組件的方法相關代碼

3.1、在父組件中使用某個組件

<Header ref="header"></Header>

 

3.2、在父組件中使用$on為子組件綁定方法

mounted () {
    // 為ref="header"的組件綁定自定義方法,方法名為addTodo
    // this.addTodo為父組件中定義的方法
    this.$refs.header.$on('addTodo', this.addTodo)
}

 

3.3、在子組件中觸發在父組件中被綁定的方法

methods: {
    addFunc () {
      if (!this.name) {
        alert('請輸入')
        return
      }
      // 在子組件中觸發在父組件中被綁定的方法
      this.$emit('addTodo', {name: this.name, checked: false})
      this.name = null
    }
}

 


免責聲明!

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



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