【问题标题】:How set the selected option on a dynamic loaded secondary select with VueJS?如何使用 VueJS 在动态加载的辅助选择上设置选定选项?
【发布时间】:2016-10-01 08:51:01
【问题描述】:

我有一个城市选择:

<select v-model="city">
    <option value="" selected>CIDADE AONDE VOCÊ ESTUDA</option>
    <option value="city1">City 1</option>
    <option value="city2">City 2</option>
    <option value="cityx">City x</option>
</select>

还有一个学校选择:

<select v-model="school">
    <option
        v-for="item in schools"
        v-bind:value="item.name"
        v-bind:selected="school == item.name"
    >
        @{{ item.name }}
    </option>
</select>

这是数据(由 Laravel Blade 视图填充),可能会或可能不会与城市和学校一起出现:

data: {
    ...
    city: '{{ Input::old('city') }}',
    school: '{{ Input::old('school') }}',
    schools: [],
},

我也有一个关于城市的手表:

watch: {
    'city': '__cityChanged',
},

这是事件处理程序:

__cityChanged: function (event)
{
    this.school = '';

    this.__fetchSchools();
},

还有抓取器:

__fetchSchools: function (event)
{
    if (this.city)
    {
        this.$http.get('/schools/' + this.city, function (schools)
        {
            this.schools = schools;
        });
    }
},

几乎一切正常,唯一的问题是,当重新加载表单(或在验证失败时重定向回)并且已经选择了城市和学校时,它会调用 __fetchSchools 并正确填写学校选择,但它没有设置学校选择选项,所以用户看到的是未选择的学校。

有没有办法使用 Vue 让它工作?

【问题讨论】:

  • 旁注:如果学校名称中有'school: '{{ Input::old('school') }}', 将中断。 school: {!! json_encode(Input::old('school')) !!}, 将使其安全。城市名称也是如此。
  • 它没有,我忘了说这是 Laravel 的东西,但是,让它工作。谢谢。
  • 听起来像是状态管理的作品。检查Vuex

标签: ajax blade vue.js vue-resource


【解决方案1】:

问题出在__cityChanged 处理程序中,这是解决方法:

__cityChanged: function (event)
{
    var city = '{{ Input::old('city') ?: (isset($subscription) ? $subscription->city : '') }}';

    if (this.city !== city)
    {
        this.school = '';
    }

    this.__fetchSchools();
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2015-12-14
    • 1970-01-01
    • 2016-07-16
    • 2018-02-28
    • 2012-12-04
    • 1970-01-01
    相关资源
    最近更新 更多