gpt4 book ai didi

javascript - Vue 2 在实例中使用外部变量

转载 作者:行者123 更新时间:2023-12-03 02:36:21 24 4
gpt4 key购买 nike

我正在开发一个 Laravel 5.5Vue 2.x 项目,该项目需要在“前端”定义一些数据并在 Vue 实例中使用它们:

首先,我有我的 View 或 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.

任何想法都会受到赞赏。

最佳答案

你可以使用created例如,生命周期钩子(Hook)

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/

关于javascript - Vue 2 在实例中使用外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48520928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com