【发布时间】:2018-01-10 15:25:04
【问题描述】:
假设我有CountrySelect 和CitySelect,其中CountrySelect 中列出了所有国家,CitySelect 中仅列出了当前选定国家/地区的那些城市...
通过新选择的国家/地区的正确方法是什么。正如我在 vuejs 文档中所读到的:
在Vue中,父子组件关系可以概括为props down,events up。父级通过 props 向下传递数据给子级,子级通过事件向父级发送消息。让我们看看它们接下来是如何工作的。
所以在这种情况下,我会检测到 CountrySelect 内的选择框的变化和触发事件 changed 以及一个国家对象。然后CountrySelect 的父组件将侦听此事件,然后在发生这种情况时更新其属性country。属性country 在父组件中被“观察到”,更改其值将导致DOM 更新,因此<city-select> 标记上称为country 的HTML 属性会更改。但是我将如何检测CitySelect 组件的属性变化,因为我需要通过 AJAX 重新加载城市。我想将country 属性放在watch 对象中的CitySelect 中,但这对我来说似乎不是一个优雅的解决方案,我觉得这样做不太合适......
<template>
<parent>
<country-select name="country_id" v-model="country"></country-select>
<city-select name="city_id" :country="country" v-model="city"></city-select>
</parent>
<template>
<script>
export default {
data: function() {
return {
country: null,
city: null,
};
}
}
</script>
我认为的其他方法是如果在父母中做这样的事情:
this.$refs.citySelect.emit('countryChanged', this.country)
或:
this.$refs.citySelect.countryChanged(this.country)
我不知道这两个是否可能...那么CountrySelect 组件告诉其兄弟组件CitySelect 更新城市列表的正确方法是什么...
【问题讨论】:
标签: javascript vue.js vuejs2