首页 文章

组件内部的VueJS Modal组件

提问于
浏览
0

我有这样的组件:

<test></test>

我声明如下:

Vue.component('test', {
  data: {
    showModal: true
  },
  methods: {
    displayComponentModalDialog: function() {
      this.showModal = true;
    }
  },
  template: `<button @click='displayComponentModalDialog'>test</button>`
});

然后将 <test></test> 组件放在 <div id="#app"> 包装器内的某个位置 .

var app = new Vue({
  router,
  el: '#app',
  // etc.    
})

现在,我想在测试组件中显示另一个组件 . 所以在这种情况下,我想在单击测试组件中的按钮后出现一个对话框 . 我无法做到这一点 .

我做的是添加一个新组件:

Vue.component('dialog', {
  template: '#dialog-template'
});

然后是下面的代码,虽然我不确定在哪里放它 .

<!-- template for the modal component -->
<script type="text/x-template" id="dialog-template">
  <transition name="dialog">
    <div class="modal-mask">
      <div class="modal-wrapper">
        <div class="modal-container">

          <div class="modal-header">
            <slot name="header">
              default header
            </slot>
          </div>

          <div class="modal-body">
            <slot name="body">
              default body
            </slot>
          </div>

          <div class="modal-footer">
            <slot name="footer">
              <button class="btn btn-primary" @click="$emit('close')">
                OK
              </button>
            </slot>
          </div>
        </div>
      </div>
    </div>
  </transition>
</script>
<!-- use the modal component, pass in the prop -->
<dialog v-if="showModal" @close="showModal = false">
  <h3 slot="header">header</h3>
  <p slot="body">
    test
  </p>
</dialog>

我尝试将此代码放在 <test></test> 中但不起作用 . 如果我把它放在组件结构中的template属性中,它只会抱怨一个根元素 .

所以很明显我错过了一些基本概念,这在VueJS中实际上是如何运作的 . 有人可以帮我澄清一下吗?谢谢 .

2 回答

  • 0

    如果要在 test 组件中添加其他组件 . 你可以使用 slot .

    您可以参考此文档:https://vuejs.org/v2/guide/components-slots.html

    例:

    //component 1
    <template>
      <div id="modal">
        // do something for your modal here.
    
        <slot></slot> // reserve area for your another html or component.
      </div>
    
    </template>
    
    // component 2
    <template>
       <your-modal-component>
         <another-component>
       </your-modal-component>
    </template>
    
  • 1

    据我所知,您的组件确实没有根标签 . 模板必须有一个根标签 .

    这不是有效的Vue模板:

    <div>
        <h1>Stuff</h1>
    </div>
    <h2>Other stuff</h2>
    

    这是一个有效的Vue模板:

    <div>
        <div>
            <h1>Stuff</h1>
        </div>
        <h2>Other stuff</h2>
    </div>
    

    请注意,在第二个版本中,我们有一个模板的单个根元素,一个 <div> ,而在第一个版本中,我们没有 .

    组件模板中同时包含 <script></script><dialog></dialog> .

相关问题