vue实现数据联动
Vue 数据联动实现方法
数据联动通常指多个表单或组件之间基于用户输入动态更新内容。Vue 提供了多种方式实现这一功能。
使用 v-model 和计算属性
通过 v-model 绑定数据,利用计算属性或 watch 监听变化并触发联动更新。
<template>
<div>
<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>
</div>
</template>
<script>
export default {
data() {
return {
selectedCountry: null,
selectedCity: null,
countries: [
{ id: 1, name: '中国' },
{ id: 2, name: '美国' }
],
cities: [
{ id: 1, countryId: 1, name: '北京' },
{ id: 2, countryId: 1, name: '上海' },
{ id: 3, countryId: 2, name: '纽约' }
]
}
},
computed: {
filteredCities() {
return this.cities.filter(city => city.countryId === this.selectedCountry)
}
}
}
</script>
使用 watch 监听变化
当需要执行异步操作或复杂逻辑时,watch 更适合。
watch: {
selectedCountry(newVal) {
this.selectedCity = null
this.fetchCities(newVal)
}
},
methods: {
fetchCities(countryId) {
// 异步获取城市数据
}
}
使用事件总线(Event Bus)
对于非父子组件间的联动,可以使用事件总线。
// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
// 组件A
EventBus.$emit('country-change', countryId)
// 组件B
EventBus.$on('country-change', (countryId) => {
this.updateCities(countryId)
})
使用 Vuex 状态管理
对于大型应用,Vuex 提供集中式状态管理。
// store.js
const store = new Vuex.Store({
state: {
selectedCountry: null
},
mutations: {
setCountry(state, countryId) {
state.selectedCountry = countryId
}
}
})
// 组件
this.$store.commit('setCountry', countryId)
// 另一个组件
computed: {
filteredCities() {
return this.cities.filter(city => city.countryId === this.$store.state.selectedCountry)
}
}
使用 provide/inject
对于深层嵌套组件,可以使用 provide/inject 实现数据联动。
// 父组件
provide() {
return {
selectedCountry: this.selectedCountry,
updateCountry: this.updateCountry
}
}
// 子组件
inject: ['selectedCountry', 'updateCountry']
以上方法可根据具体场景选择使用,简单联动使用 v-model 和计算属性即可,复杂应用建议使用 Vuex 或事件总线。







