Vue: 렌더링된 이름 있는 슬롯 내의 Vue 컴포넌트 메서드에 액세스합니다.
컴포넌트의 이름 있는 슬롯에 렌더링된 Vue 컴포넌트의 기능에 액세스하려면 어떻게 해야 합니까?
다음과 같은 구조를 가지고 있습니다.
부모 컴포넌트표시하다
...
<util-component>
<template v-slot:0>
<child-component/>
</template>
<template v-slot:1>
//Another component, and so on
</template>
</util-component>
...
Util Component(유틸리티 컴포넌트)표시하다
...
<div v-for="(comp, index) in components" :key="index">
<slot :name="index" ></slot>
</div>
...
Child Component(Child Component)표시하다
...
methods: {
myFunction () { // do something }
}
...
인UtilComponent
, 에 액세스 하고 싶다.ChildComponent
의myFunction()
(버튼을 클릭할 때는 마운트되지 않습니다).사용해보았습니다.this.$slots[0]
Util Component에는 있지만 필요한 속성(데이터 및 함수)이 없는 경우만 표시됩니다. this.$slots[0].context
완전한 Parent Component가 표시됩니다.와 함께this.$slots[0][0].context.$children[0].$children[1]
실제로 Child Component와 그 기능에 접근할 수 있지만, 이것은 매우 우회적인 것처럼 보입니다(렌더된 슬롯의 부모를 통해 해당 부모의 자녀의 자녀를 얻을 수 있습니다).
슬롯 내에 렌더링된 컴포넌트(기능)에 액세스하는 더 나은 방법이 있습니까(여기서,ChildComponent
슬롯을 제공하는 컴포넌트(여기서,UtilComponent
)?
this.$children
사용할 수 있습니다.this.$children
부터<util-component>
슬롯된 자 컴포넌트에 액세스 할 수 있습니다.
각각의 아이들이 '그것'이라고 불리는 방법을 가지고 있다고 상상해 보세요.myMethod
:
Vue.component('child-component', {
template: `<div class="child">Child</div>`,
methods: {
myMethod() {
console.log('hi')
}
}
})
인<util-component>
, 를 루프 스루프할 수 있습니다.this.$children
그러면 슬롯된 컴포넌트에 액세스할 수 있습니다.각 컴포넌트에서 이 메서드에 액세스할 수 있습니다.
methods: {
accessChildren() {
// Loop through each child component and call its function
this.$children.forEach(child => {
child.myMethod();
});
}
}
다음과 같은 레퍼런스를 제공할 수 있습니다.
<util-component>
<template v-slot:0>
<child-component ref="child1"/>
</template>
<template v-slot:1>
<child-component ref="child2"/>
</template>
</util-component>
그 후this.$refs.child1.myFunction()
컴포넌트 메서드를 호출하다
언급URL : https://stackoverflow.com/questions/66024104/vue-access-vue-component-method-inside-rendered-named-slot
'programing' 카테고리의 다른 글
C11에서의 _Generic 구문 및 사용 예 (0) | 2022.06.12 |
---|---|
Vue 라우터 링크에서 밑줄을 제거할 수 없음 (0) | 2022.06.12 |
java.lang의 원인ArrayIndexOutOfBoundsException과 이를 방지하는 방법 (0) | 2022.06.12 |
C 프로그래밍에서 정적 구조를 사용하는 이유와 시기 (0) | 2022.06.11 |
쇼트 코드에서 Vue 2 컴포넌트를 동적으로 주입합니다. (0) | 2022.06.11 |