Maramal
Maramal

Reputation: 3466

Vue 2 Using external variables inside Instance

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.

Upvotes: 0

Views: 143

Answers (1)

Mohd_PH
Mohd_PH

Reputation: 1677

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/

Upvotes: 1

Related Questions