Vue 2如何向子组件传递多动态参数仅实现school对象双向绑定
Vue 2 功能实现方案
核心实现逻辑
Vue2 自定义组件使用v-model时,默认会绑定名为value的prop,同时监听子组件触发的input事件完成双向同步。因此我们可以将需要双向绑定的school对象通过v-model传递,其余不需要双向绑定的动态参数(studentId、city)通过普通prop传递,再通过watch监听这些参数的变化触发转换逻辑即可。
1. 父组件调用写法
直接在循环渲染学生列表时绑定对应字段即可:
<template> <div v-for="(item, index) in totalStudents" :key="item.studentId"> <!-- v-model绑定需要双向同步的school对象,其余参数用普通prop传递 --> <CustomChildPicker v-model="totalStudents[index].school" :student-id="item.studentId" :city="item.city" /> </div> </template> <script> import CustomChildPicker from './CustomChildPicker.vue' export default { components: { CustomChildPicker }, data () { return { totalStudents: [{ school: { name: "Tech School", type: "highschool" }, studentId: 123, city: "seattle" }, { school: { name: "Art School", type: "university" }, studentId: 747, city: "toronto" } ] } } } </script>
2. 子组件(CustomChildPicker.vue)实现
<script> export default { props: { // v-model默认传入的prop,对应父组件绑定的school对象 value: { type: Object, required: true }, // 父组件传入的其余动态参数 studentId: { type: Number, required: true }, city: { type: String, required: true } }, watch: { // 监听city变化,触发重新转换 city: { immediate: true, // 组件初始化时就执行一次转换 handler() { this.convertAndUpdateSchool() } }, // 监听studentId变化,触发重新转换 studentId: { immediate: true, handler() { this.convertAndUpdateSchool() } }, // 如果需要监听school本身属性变化触发转换,可以加这个配置 value: { deep: true, handler() { this.convertAndUpdateSchool() } } }, methods: { convertAndUpdateSchool() { // 深拷贝school对象,避免直接修改prop违反单向数据流规则 const newSchool = JSON.parse(JSON.stringify(this.value)) // 这里写你的自定义转换逻辑,示例:根据city修改school属性 if (this.city === 'seattle') { newSchool.type = 'college' newSchool.name = 'Seattle Tech College' } else if (this.city === 'toronto') { newSchool.name = 'Toronto Art University' } // 触发input事件,更新父组件v-model绑定的school对象 this.$emit('input', newSchool) } } } </script>
注意事项
- 转换逻辑操作school对象时必须做深拷贝,不能直接修改
this.value的属性,否则会触发Vue的prop修改警告。 - 所有需要触发重新转换的动态参数,都需要在watch中添加对应监听配置。
- 如果不需要监听school本身的变化,可以删除watch中对
value的监听配置,避免不必要的重复执行。
内容的提问来源于stack exchange,提问作者Suzy
相关产品推荐
相关产品推荐

