简体   繁体   中英

Passing laravel old form data to Vue.js instance

2 weeks ago I found out i couldn't solve this and went to google for a solution which dind't really give me one, maybe the wrong type of googling not sure. Let me get to the point.

I got this piece of html and vue which makes dynamically a extra phone field when a button is pressed. the thing is when a Laravel validation fails i do not know how to get the old() data into Vue, so I can push that to the phone_number_field array.

<a v-on:click="addPhoneNumberField">
    <span class="panel-title glyphicon glyphicon-plus" aria-hidden="true"></span>
</a>
<a v-on:click="deletePhoneNumberField" v-if="phone_number_field.length > 0">
    <span class="panel-title glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>

<div class="phone row" v-for="(field, index) in phone_number_field">
    <input id="phone_number_number" type="text" class="form-control" :name="'customer[phone_numbers][' + index + '][number]'" placeholder="Number" required>
    <input id="phone_number_description" type="text" class="form-control" :name="'customer[phone_numbers][' + index + '][description]'" placeholder="Description">  
</div>

Vue part

var bindUser = new Vue({
    el: '#bindUser',

    data: {
        phone_number_field: [],
    },

    methods: {
        addPhoneNumberField() {
            this.phone_number_field.push({
                number: '',
                description: ''
            })
        },

        deletePhoneNumberField(index) {
            this.phone_number_field.splice(index, 1)
        },
    },
});

Old values are inside old('customer.phone_numbers') , so just pass it encoded into vue initiating.

Your blade template (somewhere before js include):

<script>
   var phoneValues = {!! json_encode(old('customer.phone_numbers', [])) !!};
</script>

Your js file:

data: {
    phone_number_field: phoneValues,
},

Where [] is the default value. But I think it's better to have all the initiating code in one place (blade template).

Here's an idea.. Why don't you do something along these lines:

let phone_number_field = [];
<?php if (!empty($_POST['phone_number_field']: ?>
    phone_number_field = []; //Loop foreach or whatever you need to build it
<?php endif; ?>

Then in VUE you can just initalize it with the prepouplated or empty phone_number_field you precreated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM