我正在开发 Laravel 5.5 & Vue 2.x 项目需要在“前端”中定义一些数据并在Vue实例中使用它们:
首先,我有我的观点或HTML文件:
<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>
这很好用。但在未定义formSelectedCountry
(例如)的其他页面中,Vue似乎不起作用。
我在 app.js :
中有这个data: {
...
selectedCountry: formSelectedCountry,
selectedDepartment: formSelectedDepartment,
selectedLocation: formSelectedLocation,
selectedZone: formSelectedZone,
...
}
我还尝试在这些行前面加上“预先定义”它们:
formSelectedCountry: '',
formSelectedDepartment: '',
formSelectedLocation: '',
formSelectedZone: '',
或许有一种方法可以使用selectedCountry: (formSelectedCountry ? formSelectedCountry : null
设置数据。
任何想法都表示赞赏。
答案 0 :(得分:1)
你可以使用created生命周期钩子,例如
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;
}
})