在vue js中将响应数据从组件发布到root

时间:2017-06-13 20:32:17

标签: vue.js laravel-5.3 vue-resource

我的模态框位于vue组件内。提交数据时,我希望组件将响应数据发送回父级,以便将其附加到根元素。

组件

<template>
    <div v-if="value.startsWith('new')">

    <!-- Create Client Modal -->
    <div class="modal show" id="modal-create-client" tabindex="-1" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button " class="close" data-dismiss="modal" aria-hidden="true" @click.prevent="close">&times;</button>

                    <h4 class="modal-title">Details</h4>
                </div>
                <div class="modal-body">
                    <!-- Form Errors -->
                    <div class="alert alert-danger" v-if="createForm.errors.length > 0">
                        <p><strong>Whoops!</strong> Something went wrong!</p>
                        <br>
                        <ul>
                            <li v-for="error in createForm.errors">
                                {{ error }}
                            </li>
                        </ul>
                     </div>
                     <!-- Create Client Form -->
                     <form class="form-horizontal" role="form">
                         <!-- Name -->
                         <div class="form-group">
                             <label class="col-md-3 control-label">First Name</label>
                             <div class="col-md-7">
                                 <input id="create-client-name" type="text" class="form-control" @keyup.enter="store" v-model="createForm.first">
                             </div>
                         </div>

                         <div class="form-group">
                             <label class="col-md-3 control-label">Last Name</label>
                             <div class="col-md-7">
                                 <input type="text" class="form-control" name="last" @keyup.enter="store" v-model="createForm.last">
                             </div>
                         </div>
                         <div class="form-group">
                             <label class="col-md-3 control-label">Email</label>
                             <div class="col-md-7">
                                 <input type="text" class="form-control" name="organization" @keyup.enter="store" v-model="createForm.email">
                                 <span class="help-block">Email is required for invoices</span>
                             </div>
                         </div>
                         <div class="form-group">
                             <label class="col-md-3 control-label">Organization</label>
                             <div class="col-md-7">
                                 <input type="text" class="form-control" name="organization" @keyup.enter="store" v-model="createForm.organization">
                             </div>
                         </div>
                     </form>
                 </div>

                 <!-- Modal Actions -->
                 <div class="modal-footer" v-if="value == 'newClient'">
                     <button type="button" class="btn btn-default" data-dismiss="modal" @click.prevent="close">Close</button>
                     <button type="button" class="btn btn-primary" @click="storeClient">Create</button>
                  </div>
                  <div class="modal-footer" v-else-if="value == 'newLead'">
                      <button type="button" class="btn btn-default" data-dismiss="modal" @click.prevent="close">Close</button>
                      <button type="button" class="btn btn-primary" @click="storeLead">Create</button>
                  </div>
                  <div class="modal-footer" v-else-if="value == 'newContact'">
                      <button type="button" class="btn btn-default" data-dismiss="modal" @click.prevent="close">Close</button>
                      <button type="button" class="btn btn-primary" @click="storeContact">Create</button>
                  </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>      
   export default {
       data() {
           return {
               createForm: {
                   errors: [],
                   first: '',
                   last: '',
                   email: '',
                   organization: ''
               },
           };
       },
       props: ['value'],
       /**
       * Prepare the component (Vue 1.x).
       */
       ready() {
           this.prepareComponent();
       },
       /**
       * Prepare the component (Vue 2.x).
       */
       mounted() {
           var vm = this
           this.prepareComponent();
       },
       methods: {
           /**
           * Prepare the component.
           */
           prepareComponent() {

               $('#modal-create-client').on('shown.bs.modal', () => {
                   $('#create-client-name').focus();
               });
               $("#modal-create-client").on("hide.bs.modal", function(e) {
                   $(this).removeData('bs.modal');
               });
           },
           close() {
               $('#modal-create-client').removeClass('show');
           },

           /**
           * Create a new client for the user.
           **/
           storeClient() {
               this.persistClient(
                   'post', './clients/add',
                   this.createForm, '#modal-create-client'
               );
           },
           storeLead() {
               this.persistClient(
                   'post', './leads/add',
                   this.createForm, '#modal-create-client'
               );
           },
           storeContact() {
               this.persistClient(
                   'post', './contacts/add',
                   this.createForm, '#modal-create-client'
               );
           },
           /**
           * Persist the client to storage using the given form.
           */
           persistClient(method, uri, form, modal) {
               form.errors = [];

               this.$http[method](uri, form).then(response => {
                   location.reload();
                   $(modal).modal('hide');
               }).catch(response => {
                   if (typeof response.data === 'object') {
                       form.errors = _.flatten(_.toArray(response.data));
                   } else {
                       form.errors = ['Something went wrong. Please try again.'];
                   }
               });
            },
            watch: {
                value: function (value) {
                    // update value
                    $(this.$el).val(value)
                },
            }
        }
    }
</script>

根元素

var MyComponent = Vue.component('my-ajax-component', 
    require('./components/Toolbar.vue') );
    new Vue({
        el: '#select',
        data: {
            selected: ''
        },
        components: {
            // <my-component> will only be available in parent's template
            'my-ajax-component': MyComponent
        }
    });

和我的观点

<div class="form-group clearfix">
    <div class="col-xs-12" id="select">
        {!! Form::label('client_id', 'Choose Client:', ['class' => 'control-label']) !!}
        {!! Form::select('client_id', ['newClient' => 'New Client', $clients], null, ['title' => 'Select Client', 'class' => 'form-control selectpicker', 'v-model' => 'selected', 'data-live-search' => 'true']) !!}
        <br>
        <my-ajax-component v-bind:value="selected"></my-ajax-component>
    </div>
</div>

而不是位置重新加载我想将响应数据附加到我的roo的select元素

I changed my root element to 

new Vue({
el: '#select',
data: {
    selected: '',
    data: ''
},
components: {
    // <my-component> will only be available in parent's template
    'my-ajax-component': MyComponent
},
methods: {
    handler: function(data) {
        console.log('this is my data' + data)
    }
}

我的组件现在有                         此。$发射( '数据' 接收,响应)

并将v-on放在子组件

 <my-ajax-component v-bind:value="selected"  v-on:data-received='handler(data)'></my-ajax-component>

我得到数据未定义或没有 enter image description here

我可以看到帖子中返回的数据..它是我的对象的id ...我应该json编码它 enter image description here

2 个答案:

答案 0 :(得分:1)

最简单的方法是在获得响应时使用子组件中的数据发出事件。

在孩子: this.$emit('data-received',response)

在parrent中: <child-component v-on:data-received='handler(data)'>

在parrent中的handler函数中,使用数据执行任何操作。

更新: 您的后端应返回JSON以遵循REST Api标准。 API的每个端点都应该返回JSON,即使它是简单的字符串。

答案 1 :(得分:0)

而不是

在parrent中:

<child-component v-on:data-received='handler(data)'>

我使用了In parrent:

<child-component v-on:data-received='handler'>