0

I am working on a Laravel 5.5 & Vue 2.x project which requires to define some data in the "front-end" and use them in the Vue Instance:

First, I have my view or HTML file:

<fieldset class="form-group col-md">
    <label for="country" class="control-label">Country</label>
    <select class="form-control" name="country" id="country" v-model="selectedCountry" @change="selectCountry()">
        <option :value="null" :selected="selectedCountry">Select one</option>
        <option v-for="country in countries" :value="country.id">@{{ country.name }}</option>
    </select>
</fieldset>

<script>
    var formSelectedCountry = {{ isset($property) ? $property->country_id : "null" }};
    var formSelectedDepartment = {{ isset($property) ? $property->department_id : "null" }};
    var formSelectedLocation = {{ isset($property) ? $property->location_id : "null" }};
    var formSelectedZone = {{ isset($property) ? $property->zone_id : "null" }};
</script>

This works fine. But in other pages where formSelectedCountry (for instance) is not defined Vue seems not to work.

I have this in my app.js:

data: {
    ...
    selectedCountry: formSelectedCountry,
    selectedDepartment: formSelectedDepartment,
    selectedLocation: formSelectedLocation,
    selectedZone:  formSelectedZone,
    ...
}

I have also tried to prepend these lines in order to "pre-define" them:

formSelectedCountry: '',
formSelectedDepartment: '',
formSelectedLocation: '',
formSelectedZone: '',

Or maybe there is a way to set the data with selectedCountry: (formSelectedCountry ? formSelectedCountry : null.

Any ideas are appreciated.

1 Answer 1

1

you could use created lifecycle hook, for example

var formSelectedCountry = {{ isset($property) ? $property->country_id : "null" }};
var formSelectedDepartment = {{ isset($property) ? $property->department_id : "null" }};
var formSelectedLocation = {{ isset($property) ? $property->location_id : "null" }};
var formSelectedZone = {{ isset($property) ? $property->zone_id : "null" }};
new Vue({
 data: {
 ...
 selectedCountry: '',
 selectedDepartment: '',
 selectedLocation: '',
 selectedZone:  '',
 ...
 },
 created:function(){
   this.selectedCountry = formSelectedCountry;
   this.selectedDepartment= formSelectedDepartment;
   this.selectedLocation= formSelectedLocation;
   this.selectedZone= formSelectedZone;
 }
})

https://jsfiddle.net/4yjg2LLz/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.