Vue中父子组件间的数据传递
子组件数据变化同步父组件
使用自定义事件(简单场景)
子组件:通过 $emit
触发自定义事件
<script>
export default {data() {return {childData: '初始值'}},methods: {updateParent() {// 触发自定义事件并传递数据this.$emit('data-change', this.childData);}},watch: {childData(newVal) {this.updateParent(); // 数据变化时触发}}
}
</script>
父组件:监听自定义事件
<template><child-component @data-change="handleDataChange"/>
</template><script>
export default {methods: {handleDataChange(newValue) {console.log('收到子组件数据:', newValue);this.parentData = newValue; // 更新父组件数据}}
}
</script>
使用 Vuex/Pinia 状态管理(复杂场景)
// store.js (以vuex为例)
export default new Vuex.Store({state: {sharedData: null},mutations: {updateData(state, payload) {state.sharedData = payload}}
})
子组件
<script>
export default {
..........................methods: {updateStore() {this.$store.commit('updateData', this.childData)}}
}
</script>
父组件
<template><div>{{ sharedData }}</div>
</template><script>
import { mapState } from 'vuex'export default {computed: {...mapState(['sharedData'])}
}
</script>
父组件数据变化同步子组件
Props 传递
父组件通过 props
向子组件传递数据,父数据变化时子组件会自动更新。
注意:子组件不要直接修改props传递的值,通过$emit通知父组件修改。
<!-- 父组件 -->
<template><Child :message="parentMsg" />
</template><script>
export default {data() {return { parentMsg: "初始值" };},mounted() {setTimeout(() => {this.parentMsg = "父组件修改后的值"; // 修改后子组件自动更新}, 2000);}
};
</script><!-- 子组件 -->
<template><div>{{ message }}</div> <!-- 显示父组件传递的值 -->
</template><script>
export default {props: ['message'] // 声明接收父组件数据
};
</script>
Vuex/Pinia 状态管理
全局状态管理,父子组件共享同一状态。
// store.js (以 Pinia 为例)
export const useStore = defineStore('main', {state: () => ({ count: 0 }),actions: {updateCount(val) { this.count = val; }}
});
<!-- 父/子组件共用方式 -->
<script setup>
import { useStore } from './store';
const store = useStore();
</script><template><div>{{ store.count }}</div><button @click="store.updateCount(10)">修改状态</button>
</template>
直接修改子组件数据
通过 ref
直接操作子组件(破坏数据流,仅应急使用)
<template><ChildComponent ref="child" /><button @click="forceUpdate">强制修改</button>
</template><script>
export default {methods: {forceUpdate() {this.$refs.child.internalData = "新值"; // 直接修改子组件数据}}
};
</script>