Vue組件之間的通訊

1,父組件向子組件傳參函數

  • 在父組件中,找到須要傳遞的子組件,並把消息賦值
<template>
<div> I am a 'a' component
<com-b :prop-data="0" msgfromfather="I am your father"></com-b>
</div>

</template>


<script>
import comB from './b'
export default {
    components: {comB},
    props: ['propData']
}
</script>
  • 在子文件中使用props

Prop 是你能夠在組件上註冊的一些自定義特性。當一個值傳遞給一個 prop 特性的時候,它就變成了那個組件實例的一個屬性。this

<template>
<div>
  <div>{{msg}}</div>
  <div>{{msgfromfather}}</div>
  <button v-on:click="onClickMe">click me </button>
  </div>
</template>

<script>
 export default{
 data: function(){
      return {
      msg: 'this is Part B!'
      }
  },
      props: [
  'msgfromfather'   //註冊父組件傳遞的消息
  ],
  methods: {
      onClickMe:  function(){
      console.log(this.msgfromfather)//能夠直接調用
      }
  }
 }
</script>

2,子組件向父組件傳遞消息spa

方法一:利用自定義事件 on和emitcode

在父組件中自定義函數v-on:child-tell-me="listenToMyBoy"component

在子組件中觸發定義的事件this.$emit("child-tell-me", this.msg), msg就是子組件傳遞的信息blog

在父組件實現以前定義的方法‘listenToMyBoy’事件

//父組件
<template>
<div> I am a 'a' component
<p>Child component b tells me: {{childWords}}</p>
<com-b :prop-data="0" msgfromfather="I am your father" v-on:child-tell-me="listenToMyBoy"></com-b>
</div>

</template>


<script>
import comB from './b'
export default {
    data: function(){
        return {
        'childWords': '' //要在頁面使用子組件傳遞的信息,須要聲明一個參數
        }
    },
    components: {comB},
    props: ['propData'],
    methods: {
        listenToMyBoy: function(msg){
            this.childWords = msg;//信息傳遞給聲明的參數
        }
    }
}
</script>
//子組件
<template> <div> <div>{{msg}}</div> <div>{{msgfromfather}}</div> <button v-on:click="onClickMe">click me </button> </div> </template> <script> export default{ data: function(){ return { msg: 'this is Part B!' } }, props: [ 'msgfromfather' ], methods: { onClickMe: function(){ //console.log(this.msgfromfather) this.$emit("child-tell-me", this.msg) } } } </script>

若是是跨多層父子組件通訊的話,$emit 並無什麼用。ip

相關文章
相關標籤/搜索