Programing

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

crosscheck 2020. 8. 7. 07:59
반응형

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


문맥

Vue 2.0에서 문서 및 기타 는 부모에서 자식으로의 의사 소통이 소품을 통해 발생한다는 것을 명확하게 나타냅니다.

질문

부모는 소품을 통해 이벤트가 발생했다고 자식에게 어떻게 알립니 까?

이벤트라는 소품 만 볼까요? 그것은 옳지 않다고 느끼거나 대안도 아닙니다 ( $emit/ $on는 자식에서 부모로, 허브 모델은 먼 요소를위한 것입니다).

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


자식 구성 요소에 a를 제공하고 자식 구성 요소에서 직접 메서드를 호출하는 데 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);
    }
  }
})

자세한 내용 은 refs에 대한 Vue 문서를 참조하세요 .


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

var Child = {
  template: '<div>{{counter}}</div>',
  props: ['canI'],
  data: function () {
    return {
      counter: 0
    };
  },
  watch: {
    canI: function () {
      if (this.canI) {
        ++this.counter;
        this.$emit('increment');
      }
    }
  }
}
new Vue({
  el: '#app',
  components: {
    'my-component': Child
  },
  data: {
    childState: false
  },
  methods: {
    permitChild: function () {
      this.childState = true;
    },
    lockChild: function () {
      this.childState = false;
    }
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
<div id="app">
<my-component :can-I="childState" v-on:increment="lockChild"></my-component>
<button @click="permitChild">Go</button>
</div>

정말로 이벤트를 아이에게 전달하고 싶다면 버스 (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 스토어를 사용하여 변수 (일명 상태)를 보거나 액션을 직접 트리거 (일명 디스패치)하십시오.


.NET Framework 동안 자식에서 바인딩을 사용 하는 이벤트 버스 접근 방식이 마음에 들지 않았습니다 . 왜? 후속 호출 (사용하고 있음 )은 메시지 처리기를 두 번 이상 바인딩하여 메시지 당 여러 응답을 유도합니다.$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>

A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from 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>

The parent keeps track of the child handler functions and calls whenever necessary.


The below example is self explainatory. where refs and events can be used to call function from and to parent and child.

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

I think we should to have a consideration about the necessity of parent to use the child’s methods.In fact,parents needn’t to concern the method of child,but can treat the child component as a FSA(finite state machine).Parents component to control the state of child component.So the solution to watch the status change or just use the compute function is enough


You could use a mixin to set a shared data attribute. Change it in the parent, watch it in the child:

// mixin
export default {
  data() {
    return  {
      clicked: false
    }
  }
}

// parent
export default {
  mixins: [myMixin],
  methods: {
    btnClick() {
      this.clicked = true
    }
  }
}

// child
export default {
  mixins: [myMixin],
  watch: {
    clicked(val) {
      if(val) {
        // yay
      }
    }
  }
}

참고URL : https://stackoverflow.com/questions/42632711/how-to-call-function-on-child-component-on-parent-events

반응형