vue实现联动效果
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, countryId: 1, name: 'Beijing' },
{ id: 2, countryId: 1, name: 'Shanghai' },
{ id: 3, countryId: 2, name: 'New York' }
]
}
},
computed: {
filteredCities() {
return this.cities.filter(city => city.countryId === this.selectedCountry)
}
}
}
</script>
使用 watch 监听数据变化
通过 watch 监听数据变化,执行联动逻辑。
<template>
<input v-model="price" type="number" />
<input v-model="quantity" type="number" />
<p>Total: {{ total }}</p>
</template>
<script>
export default {
data() {
return {
price: 0,
quantity: 0,
total: 0
}
},
watch: {
price(newVal) {
this.total = newVal * this.quantity
},
quantity(newVal) {
this.total = this.price * newVal
}
}
}
</script>
使用事件触发联动
通过自定义事件实现父子组件或兄弟组件之间的联动。
<!-- ParentComponent.vue -->
<template>
<ChildComponent @change="handleChange" />
<p>Selected: {{ selectedValue }}</p>
</template>
<script>
export default {
data() {
return {
selectedValue: null
}
},
methods: {
handleChange(value) {
this.selectedValue = value
}
}
}
</script>
<!-- ChildComponent.vue -->
<template>
<select @change="emitChange">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</template>
<script>
export default {
methods: {
emitChange(e) {
this.$emit('change', e.target.value)
}
}
}
</script>
使用 Vuex 管理共享状态
对于复杂应用,可以使用 Vuex 管理共享状态,实现组件间联动。
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
selectedItem: null
},
mutations: {
setSelectedItem(state, payload) {
state.selectedItem = payload
}
}
})
<!-- ComponentA.vue -->
<template>
<select @change="updateItem">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
</template>
<script>
export default {
methods: {
updateItem(e) {
this.$store.commit('setSelectedItem', e.target.value)
}
}
}
</script>
<!-- ComponentB.vue -->
<template>
<p>Selected item: {{ selectedItem }}</p>
</template>
<script>
export default {
computed: {
selectedItem() {
return this.$store.state.selectedItem
}
}
}
</script>
注意事项
- 简单联动优先使用计算属性和
v-model - 复杂逻辑或异步操作使用
watch - 组件间通信考虑使用事件或 Vuex
- 避免过度使用 Vuex,简单场景可用
provide/inject







