[javascript] 부모 이벤트의 자식 구성 요소에서 함수를 호출하는 방법

문맥

Vue 2.0에서 문서와 기타 문서 는 부모와 자식 사이의 커뮤니케이션이 소품을 통해 이루어짐을 분명히 나타냅니다.

질문

부모는 자녀에게 소품을 통해 사건이 발생했음을 어떻게 알립니 까?

이벤트라는 소품을 볼까요? 그것은 옳지 않거나 대안이 아닙니다 ( $emit/ $on는 어린이에서 부모로, 허브 모델은 먼 요소를 위해).

부모 컨테이너가 있으며 API에 대해 특정 작업을 수행해도된다는 것을 자식 컨테이너에 알려 주어야합니다. 기능을 트리거 할 수 있어야합니다.



답변

자식 구성 요소를 제공 ref하고 사용하십시오$refs 대한 메서드를 직접 호출하는 데 합니다.

html :

<div id="app">
  <child-component ref="childComponent"></child-component>
  <button @click="click">Click</button>
</div>

자바 스크립트 :

var ChildComponent = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
    setValue: function(value) {
        this.value = value;
    }
  }
}

new Vue({
  el: '#app',
  components: {
    'child-component': ChildComponent
  },
  methods: {
    click: function() {
        this.$refs.childComponent.setValue(2.0);
    }
  }
})

자세한 내용 은 심판에 대한 Vue 설명서를 참조하십시오 .


답변

당신이 설명하는 것은 부모의 상태 변화입니다. 당신은 소품을 통해 아이에게 전달합니다. 당신이 제안한대로, 당신은 watch그 소품 을 것 입니다. 자식이 조치를 취하면을 통해 부모에게 알리고 emit부모는 다시 상태를 변경할 수 있습니다.

실제로 어린이에게 이벤트를 전달하려면 버스 (Vue 인스턴스 일뿐)를 만들고이를 자식으로 소품으로 전달하면됩니다 .


답변

$emit및 을 사용할 수 있습니다 $on. @RoyJ 코드 사용 :

html :

<div id="app">
  <my-component></my-component>
  <button @click="click">Click</button>
</div>

자바 스크립트 :

var Child = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
    setValue: function(value) {
        this.value = value;
    }
  },
  created: function() {
    this.$parent.$on('update', this.setValue);
  }
}

new Vue({
  el: '#app',
  components: {
    'my-component': Child
  },
  methods: {
    click: function() {
        this.$emit('update', 7);
    }
  }
})

실행 예 : https://jsfiddle.net/rjurado/m2spy60r/1/


답변

시간이 있으면 Vuex 스토어를 사용하여 변수 (일명 상태)를 보거나 작업을 직접 트리거 (일명 디스패치)하십시오.


답변

동안 아이에서 바인딩을 사용 하는 이벤트 버스 접근 방식이 마음에 들지 않았습니다 . 왜? 후속 통화 (사용중인$oncreatecreatevue-router )은 메시지 처리기를 두 번 이상 바인딩하여 메시지 당 여러 응답을 유발합니다.

소품을 부모에서 자녀에게 전달하고 재산 감시자를 자녀에게 배치하는 정통 솔루션은 조금 더 효과적이었습니다. 문제는 아동이 가치 전환에만 행동 할 수 있다는 것입니다. 동일한 메시지를 여러 번 전달하면 전환을 강제하기 위해 일종의 부기 관리가 필요하므로 자녀가 변경 사항을 선택할 수 있습니다.

배열에서 메시지를 줄 바꿈하면 값이 동일하더라도 자식 감시자를 트리거합니다.

부모의:

{
   data: function() {
      msgChild: null,
   },
   methods: {
      mMessageDoIt: function() {
         this.msgChild = ['doIt'];
      }
   }
   ...
}

아이:

{
   props: ['msgChild'],
   watch: {
      'msgChild': function(arMsg) {
         console.log(arMsg[0]);
      }
   }
}

HTML :

<parent>
   <child v-bind="{ 'msgChild': msgChild }"></child>
</parent>


답변

자식 구성 요소에서 메서드를 호출하는 간단한 분리 방법은 자식에서 처리기를 생성 한 다음 부모에서 호출하는 것입니다.

var Child = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
  	setValue(value) {
    	this.value = value;
    }
  },
  created() {
    this.$emit('handler', this.setValue);
  }
}

new Vue({
  el: '#app',
  components: {
    'my-component': Child
  },
  methods: {
  	setValueHandler(fn) {
    	this.setter = fn
    },
    click() {
    	this.setter(70)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

<div id="app">
  <my-component @handler="setValueHandler"></my-component>
  <button @click="click">Click</button>
</div>

부모는 자식 핸들러 함수를 추적하고 필요할 때마다 호출합니다.


답변

아래 예제는 자체 설명입니다. 여기서 refs와 이벤트는 부모와 자식에서 함수를 호출하는 데 사용될 수 있습니다.

// PARENT
<template>
  <parent>
    <child
      @onChange="childCallBack"
      ref="childRef"
      :data="moduleData"
    />
    <button @click="callChild">Call Method in child</button>
  </parent>
</template>

<script>
export default {
  methods: {
    callChild() {
      this.$refs.childRef.childMethod('Hi from parent');
    },
    childCallBack(message) {
      console.log('message from child', message);
    }
  }
};
</script>

// CHILD
<template>
  <child>
    <button @click="callParent">Call Parent</button>
  </child>
</template>

<script>
export default {
  methods: {
    callParent() {
      this.$emit('onChange', 'hi from child');
    },
    childMethod(message) {
      console.log('message from parent', message);
    }
  }
}
</script>