1. 组件间的数据传递
- 父传子:通过
props
将需要的信息(如事件名称、初始绑定状态等)传递给子组件。
- 子传父:使用
$emit
触发自定义事件,将子组件的状态变化通知给父组件。
2. 事件处理逻辑
- 父组件:在
created
或 mounted
钩子函数中,根据子组件通过 $emit
传递的状态,使用 $on
动态绑定和解绑事件。
- 子组件:在自身状态发生变化时,通过
$emit
通知父组件,以便父组件进行相应的事件绑定或解绑操作。
3. 关键代码片段
父组件
<template>
<div>
<child-component :initial-binding="initialBinding" @child-state-change="handleChildStateChange"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
initialBinding: true,
// 假设这里有一个要绑定的事件处理函数
someEventHandler: () => {
console.log('事件被触发');
}
};
},
created() {
if (this.initialBinding) {
this.$on('someEvent', this.someEventHandler);
}
},
methods: {
handleChildStateChange(state) {
if (state) {
this.$on('someEvent', this.someEventHandler);
} else {
this.$off('someEvent', this.someEventHandler);
}
}
}
};
</script>
子组件
<template>
<div>
<button @click="toggleState">切换状态</button>
</div>
</template>
<script>
export default {
props: {
initialBinding: {
type: Boolean,
default: false
}
},
data() {
return {
internalState: this.initialBinding
};
},
methods: {
toggleState() {
this.internalState = !this.internalState;
this.$emit('child-state-change', this.internalState);
}
}
};
</script>