【问题标题】:Open modal for add element from child component VueJs从子组件VueJs添加元素的打开模式
【发布时间】:2020-03-29 01:40:24
【问题描述】:

我有一个按钮,应该从一个孩子打开一个模式,添加一个新客户。

如果我的代码只是在父级中,它可以工作,但我尝试在子级中实现它。

家长

<b-button @click="openModal">Add new customer</b-button>
<add-new-customer ref="modal" v-if="addCustomer"></add-new-customer>

openModal() {
   this.$refs.modal.openModalCh()
},

儿童

<b-modal
        id="modal-prevent-closing"
        ref="modal"
        title="Add new customer"
        @ok="addCustomer"
>
...code..
</b-modal>
    <add-new-customer ref="modal" v-if="addCustomer" @added="onAddCustomer"></add-new-customer>
    addCustomer() {
       ..code for post a new customer..
    }
    openModal() {
       this.$refs.modal.openModalCh()
    },

【问题讨论】:

    标签: vue.js vuejs2 bootstrap-vue


    【解决方案1】:

    您可以将$attr 绑定到包含从父级传递给子级的所有属性的模式。在这种情况下,我们将其用作 ID。

    通过这种方式,您可以在父项中为模态框提供一个 ID,并使用该 ID 打开没有引用的模态框。

    家长

    <template>
      <div>
          <!-- Use the id that you've given the modal -->
          <b-btn @click="$bvModal.show('add-customer')">Open Modal</b-btn>
          <add-customer-modal id="add-customer" title="add old customer"></add-customer-modal>
      </div>
    </template>
    
    <script>
    import AddCustomerModal from './components/AddCustomerModal.vue'
    
    export default {
      name: "App",
      components: {
        AddCustomerModal
      }
    };
    </script>
    

    AddCustomerModal.vue(子)

    <template>
      <b-modal
        v-bind="$attrs"
        title="Add new customer"
        @ok="addCustomer"
      ></b-modal>
    </template>
    
    <script>
      export default {
        methods: {
          addCustomer() {
            /* Insert logic here */
            console.log('Customer added!')
          }
        }
      }
    </script>
    

    【讨论】:

    • 它打开了,但我在 @ok="addCustomer" 上收到错误,它没有到达那里。我现在在看,为什么。
    【解决方案2】:

    您可以通过将您的孩子作为组件注入您的父母来解决您的问题。并以props 为例。

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2018-06-10
      • 2019-03-22
      • 2020-10-18
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 2021-08-21
      • 2019-09-30
      相关资源
      最近更新 更多