programing

Vue: 루트 요소 컨텐츠 및 컨텐츠 배포 슬롯

prostudy 2022. 4. 27. 21:36
반응형

Vue: 루트 요소 컨텐츠 및 컨텐츠 배포 슬롯

Vue 생성자에 대한 옵션의 Vue 문서에는 "템플릿에 컨텐츠 배포 슬롯이 없는 경우" 루트 요소의 컨텐츠가 표시되지 않는다고 명시되어 있다.그러나 다음과 같은 글을 쓰려고 할 때:

new Vue({
  el: '#app',
  template: `
    <div>
      <h1>App title</h1>
      <slot></slot>
    </div>
  `
});
<html>

<body>
  <div id="app">
    App content
  </div>
  <script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
</body>

</html>

루트 요소의 내용은 포함되지 않는데, 올바른 방법은 무엇인가?

또는 vue 인스턴스를 만들 때 프로그래밍 방식으로 추가 컨텐츠를 주입하는 방법을 선택하십시오.

어떤 면에서는, 뿌리가 정규 성분처럼 동작하지 않는다: 합격할 수도 없고, 사용할 수도 없다.<slot>s 템플릿에 직접 포함(관련: vue/#4485).

현재 소스를 살펴보십시오. 는 함수의해 해결되며, 그 지점에서 해결됨.resolveSlots루트 구성 요소로 호출된다.$options._renderChildren이다undefined슬롯이 해결되지 않는 경우.그 시점 이후가 중요한 것은 아니지만, 사실상, 뿌리 성분은 절대 그 성분을 채우지 않는다.$options._renderChildren.

라고 전해져 오고 있다.<slot>논리를 다루는 것은 일을 좀 복잡하게 만들었고, 그래서 아마 그것은 설계 결정이었을 것이다.

대체 솔루션

질문 내용을 처리하는 데 일반적으로 사용되는 패턴은 다른 구성 요소로 내용을 포장하는 것이다(예:<app>) 구성 요소와 거기서부터.

Vue.component('app', {
  template: `<div>
    <h2>I'm the &lt;app&gt; component title</h2>
    <slot>app slot default text</slot>
  </div>`
});
new Vue({
  el: '#app'
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<div id="app">
  <app>
    I'm the contents of app's template and was declared in root
  </app>
</div>

어떻게 하는지 보라.this.$slots비록 그것이 가지고 있음에도 불구하고 뿌리채택이 되지 않는다.<slot>아래의 데모에서 s를 참조하십시오.

Vue.component('app', {
  template: `<div>
    <h2>I'm the &lt;app&gt; component title</h2>
    <slot>app slot default text</slot>
  </div>`,
  created() {
    console.log("<app>'s VDOM children (LENGTH): ", this.$options._renderChildren.length);
    console.log("<app>'s slots (LENGTH): ", this.$slots.default.length);
  }
});
new Vue({
  el: '#app',
  created() {
    console.log("root's VDOM children: ", this.$options._renderChildren);
    console.log("root's slots: ", this.$slots);
  }
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
  <app>
    I'm the contents of app's template
  </app>

  <slot>root's slot's default content, won't make it into $slots, check the console</slot>
</div>

참조URL: https://stackoverflow.com/questions/49046697/vue-root-element-content-and-content-distribution-slots

반응형