vue实现联动 get
Vue 实现联动功能的方法
联动功能通常指多个组件或元素之间的动态交互,例如选择框、表单字段等的联动更新。以下是几种常见的实现方式:
使用 v-model 和计算属性
通过 v-model 绑定数据,结合计算属性动态更新关联字段的值。

<template>
<select v-model="selectedCountry">
<option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>
<select v-model="selectedCity">
<option v-for="city in filteredCities" :value="city.id">{{ city.name }}</option>
</select>
</template>
<script>
export default {
data() {
return {
selectedCountry: null,
selectedCity: null,
countries: [
{ id: 1, name: 'China' },
{ id: 2, name: 'USA' }
],
cities: [
{ id: 1, name: 'Beijing', countryId: 1 },
{ id: 2, name: 'Shanghai', countryId: 1 },
{ id: 3, name: 'New York', countryId: 2 }
]
}
},
computed: {
filteredCities() {
return this.cities.filter(city => city.countryId === this.selectedCountry)
}
}
}
</script>
使用 watch 监听数据变化
通过 watch 监听某个字段的变化,动态更新其他字段的值。
<script>
export default {
data() {
return {
selectedCountry: null,
selectedCity: null,
cities: []
}
},
watch: {
selectedCountry(newVal) {
this.selectedCity = null
this.fetchCities(newVal)
}
},
methods: {
fetchCities(countryId) {
// 模拟异步请求
setTimeout(() => {
this.cities = [
{ id: 1, name: 'Beijing' },
{ id: 2, name: 'Shanghai' }
]
}, 500)
}
}
}
</script>
使用事件触发联动
通过自定义事件实现父子组件之间的联动。

<!-- ParentComponent.vue -->
<template>
<CountrySelect @country-change="handleCountryChange" />
<CitySelect :country-id="selectedCountry" />
</template>
<script>
export default {
data() {
return {
selectedCountry: null
}
},
methods: {
handleCountryChange(countryId) {
this.selectedCountry = countryId
}
}
}
</script>
<!-- CountrySelect.vue -->
<script>
export default {
methods: {
emitChange(event) {
this.$emit('country-change', event.target.value)
}
}
}
</script>
使用 Vuex 管理状态
对于复杂应用,可以使用 Vuex 集中管理联动状态。
// store.js
export default new Vuex.Store({
state: {
selectedCountry: null,
cities: []
},
mutations: {
setCountry(state, countryId) {
state.selectedCountry = countryId
},
setCities(state, cities) {
state.cities = cities
}
},
actions: {
fetchCities({ commit }, countryId) {
// 异步获取城市数据
commit('setCities', [
{ id: 1, name: 'Beijing' },
{ id: 2, name: 'Shanghai' }
])
}
}
})
// Component.vue
<script>
import { mapState, mapActions } from 'vuex'
export default {
computed: {
...mapState(['selectedCountry', 'cities'])
},
methods: {
...mapActions(['fetchCities'])
},
watch: {
selectedCountry(newVal) {
this.fetchCities(newVal)
}
}
}
</script>
使用第三方库实现复杂联动
对于更复杂的联动需求,可以考虑使用如 vue-select、element-ui 等 UI 库提供的现成组件。
<template>
<el-cascader
:options="options"
v-model="selectedOptions"
/>
</template>
<script>
export default {
data() {
return {
selectedOptions: [],
options: [
{
value: 'china',
label: 'China',
children: [
{ value: 'beijing', label: 'Beijing' },
{ value: 'shanghai', label: 'Shanghai' }
]
}
]
}
}
}
</script>
以上方法可根据具体需求选择使用,简单联动可使用计算属性或 watch,复杂场景建议使用状态管理或现成组件库。






