【问题标题】:VueJS Modal component inside component组件内的VueJS Modal组件
【发布时间】:2019-04-16 14:29:52
【问题描述】:

我有一个这样的组件:

<test></test>

我声明如下:

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

然后将&lt;test&gt;&lt;/test&gt; 组件放置在&lt;div id="#app"&gt; 包装器内的某个位置。

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>

我尝试将此代码放在&lt;test&gt;&lt;/test&gt; 中,但不起作用。如果我把它放在组件结构中的模板属性中,它只会抱怨一个根元素。

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

【问题讨论】:

  • Is是测试组件displayComponentModalDialog内部的一个方法:function() { this.showModal = true; },

标签: vue.js vue-component


【解决方案1】:

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

这不是一个有效的 Vue 模板:

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

这是一个有效的 Vue 模板:

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

请注意,在第二个版本中,我们有一个模板的单个根元素 &lt;div&gt;,而在第一个版本中我们没有。

您的组件模板中同时拥有&lt;script&gt;&lt;/script&gt;&lt;dialog&gt;&lt;/dialog&gt;

【讨论】:

    【解决方案2】:

    如果您想在 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>
    

    【讨论】:

      猜你喜欢
      • 2019-05-21
      • 2020-04-19
      • 2020-09-16
      • 2018-11-22
      • 2016-12-21
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多