鍍金池/ 問答/HTML/ vue這個里面誰是父組件誰是子組件?

vue這個里面誰是父組件誰是子組件?

父組件是counter-event-example嗎? 子組件是button-counter嗎?counter-event-example不就是一個div標簽嗎 哪里是組件了?v-on是在監(jiān)聽嗎?如果是這樣的話不是自己監(jiān)聽自己嗎?一直分不清哪個是父組件哪個是子組件也搞不清emit的用法怎么辦?

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment1="incrementTotal"></button-counter>
  <button-counter v-on:increment1="incrementTotal"></button-counter>
</div>


Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1 //組件模板中的counter
      this.$emit('increment1')//觸發(fā)自定義事件,這里的參數(shù)是自定義事件名稱
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1  //父實例下的total
    }
  }
})
回答
編輯回答
放開她

你看你注冊了一個組件 button-counter,然后這個組件在 counter-event-example 里面調(diào)用了,所以它是 counter-event-example 的子組件。
之后你想在 button-counter 里面調(diào)用父組件 counter-event-example 的方法,就要在使用子組件 button-counter 的時候把父組件的方法傳進去,然后在子組件中 $emit 這個方法傳入?yún)?shù)調(diào)用。

2018年1月4日 13:51
編輯回答
維他命

對,父組件是counter-event-example, 子組件是button-counter,父子組件就是在注冊一個組件的時候引用了另一個組件,

<component1>
    <component2></component2>
</component1>

component1 component2是兄弟組件,你的那個是父子組件。父組件那個是監(jiān)聽,監(jiān)聽子組件,在子組件的事件中去寫this.$emit(),就會觸發(fā)incrementTotal這個自定義事件。

2018年7月5日 06:33
編輯回答
涼心人

父組件可以使用 props 把數(shù)據(jù)傳給子組件。
子組件可以使用 $emit 觸發(fā)父組件的自定義事件。
一般來說應該是this.$emit('xxxx',[data])
xxxx是自定義事件名,data是傳遞的可選數(shù)據(jù),空也可以。
父組件應該通過v-on:xxxx='事件'綁定一個事件,當子組件this.$emit被調(diào)用時觸發(fā)這個'事件'。
至于誰是子組件誰是父組件,看調(diào)用就可以了,誰被調(diào)用誰就是子組件。

2017年4月10日 21:28