vue子组件访问父组件
时间: 2023-11-06 13:05:16 浏览: 38
在Vue中,子组件访问父组件有多种方式。其中,最常见的有使用事件和属性传递的方式。
1. 使用事件传递:
在父组件中,通过在子组件上绑定事件,当子组件触发该事件时,父组件可以捕获到该事件并执行相应的方法。具体代码如下所示:
父组件:
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('调用父组件方法成功');
}
}
};
</script>
子组件:
<template>
<div>
<button @click="$emit('fatherMethod')">调用父组件方法</button>
</div>
</template>
<script>
export default {
methods: {
// 子组件触发事件
handleClick() {
this.$emit('fatherMethod');
}
}
};
</script>
2. 使用属性传递:
在父组件中,可以通过属性的方式将父组件的方法传递给子组件,在子组件中通过调用该属性来访问父组件的方法。具体代码如下所示:
父组件:
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('调用父组件方法成功');
}
}
};
</script>
子组件:
<template>
<div>
<button @click="fatherMethod">调用父组件方法</button>
</div>
</template>
<script>
export default {
props: ['fatherMethod']
};
</script>