如何在vue组件上显示在combobox动态编辑的值?

时间:2018-03-17 07:37:01

标签: javascript vue.js vuejs2 vue-component vuex

我有两个组件

我的第一个组件(父组件)是这样的:

<template>
    <div>
        ...
            <form class="form-horizontal" id="form-profile" @submit.prevent="submitFormProfile">
                ...
                <form-select id="province" name="province" v-model="province" :options="provinces" v-on:triggerChange="changeProvince" :is-required="isRequired" model="1">Province</form-select>
                <form-select id="regency" name="regency" v-model="regency" :options="regencies" v-on:triggerChange="changeRegency" :is-required="isRequired" model="1">Regency</form-select>
                <form-select id="district" name="district" v-model="district" :options="districts" v-on:triggerChange="changeDistrict" :is-required="isRequired" model="1">District</form-select>
                ....
            </form>
        ...
    </div>
</template>
<script>
    export default {
        data() {
            return {
                province: null,
                regency: null,
                district: null,
            }
        },
        mounted() {
            ...
            this.getUserLogin()
            .then((response) => {
                let user = response.data
                this.province = user.address_list.province
                this.regency = user.address_list.regency
                this.district = user.address_list.district
            })
            .catch(error => {
                console.log(error)
            });
        },
        ...
    }
</script>

我的第二个组件(子组件)是这样的:

<template>
    <div class="form-group">
        <label :for="id" class="col-sm-3 control-label"><slot></slot></label>
        <div class="col-sm-9">
            <select :id="id" :name="name" class="form-control" v-model="selected" v-on:change="applySelected">
                <option disabled value="">Please select one</option>
                <option v-for="option in options" :value="option.id">{{option.name}}</option>
            </select>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['value', ...],
        data() {
            return {
                selected: this.value|| ''
            }
        },
        mounted() {
            console.log(this.value)
        }
        ...
    }
</script>

当组件执行时,它将调用ajax来获取省省,摄政,区

如果我在响应ajax(父组件)中console.log(response.data),我得到值

但如果我在第二个组件中console.log(this.value),我就找不到该值。值= null

这似乎发生了,因为在调用子组件时,ajax进程尚未完成

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

选项1 - 添加观察者

问题是,您只在初始化组件时在selected: this.value || ''中设置了data。要让它更新,您还需要添加一个观察程序,如下所示:

watch: {
  value(newValue) {
    this.selected = newValue;
  }
}

每当父母中的selected道具发生变化时,这将更新selected道具。

选项2 - 直接参考道具

你可以完全摆脱value并在孩子身上使用{{1}}。它始终与父母保持同步。